Sygna: practice management for Polish law firms

Stage A of a system meant to merge with Galena (PLAN.md §3). Same stack,
same layering, same identity/node/authz layer copied byte-identical so the
Stage B convergence is a data move rather than a rewrite.

What a firm gets:
- Matters as leaves of Galena's node tree, each pointing at a Galena project
  for its case file.
- A conflict-of-interest check that BLOCKS matter creation until decided, with
  Polish name normalisation (diacritics folded, declension stemmed, containment
  rather than Jaccard so "Kowalski" matches "Kowalski Nowak i Wspólnicy").
- Ethical walls that beat every inherited grant including instance admin, and
  are administered from the parent container so nobody can lock themselves out.
- Correspondence with a legally binding service date that is set once and never
  inferred; deadlines derived from it keep a pointer back and record their basis
  in words. Dual control on statutory and court deadlines.
- Time in integer minutes, money in integer grosze, rates resolved through
  matter override -> matter card -> client card -> firm card -> house setting,
  with the resolution explaining itself.
- Billing: disbursements with pass-through VAT, draft -> approve -> issue,
  credit notes that release the work rather than writing it off, and client
  money on a ledger a CHECK constraint stops going negative.
- Reports: realisation, utilisation against real Polish working days,
  profitability (honest "incomplete" without a cost rate), lock-up, aged debt.
- Court-fee and koszty-zastępstwa calculators whose schedules are auditable data
  carrying their statute, their version and a "verify this" note.
- KRS and Biała lista connectors. The KRS API masks natural persons' names, so
  officers are reported as redacted and never invented into party records.
- An idempotent reminder engine; every reminder is deduplicated by a database
  constraint, so the scheduler is safe to run at any frequency.

209 tests pass twice in a row against PostgreSQL 16 (127 DB-free, 82
integration), 126 routes, 29 tables, least-privilege grants, licence gate clean.

Known caveats, all documented in CLAUDE.md and shown in the UI:
- The fee schedules need a lawyer's verification.
- The VAT treatment of disbursements needs an accountant's sign-off.
- Galena integration is untested against a live Galena.
- "Sygna" has had no trademark or domain clearance.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-13 11:50:33 +02:00
co-authored by Claude Opus 5
commit bd2f2470fa
114 changed files with 17315 additions and 0 deletions
+81
View File
@@ -0,0 +1,81 @@
# ─────────────────────────────────────────────────────────────────────────────
# Sygna — copy to .env and edit. On Windows write it WITHOUT a BOM:
# [System.IO.File]::WriteAllText("$PWD\.env", (Get-Content .env.example -Raw))
# (PowerShell's Out-File -Encoding utf8 adds a BOM, which pydantic-settings then
# folds into the first key name.)
# ─────────────────────────────────────────────────────────────────────────────
# Core. Defaults fail closed: production hides error detail and enables Secure cookies.
# Set development explicitly for local plain-HTTP work.
APP_ENV=production
APP_BASE_URL=http://localhost
# ── Database ─────────────────────────────────────────────────────────────────
# Runtime uses the least-privilege `app` role; Alembic uses `migrator`.
POSTGRES_DB=sygna
POSTGRES_PASSWORD=change_me_super
DB_APP_PASSWORD=change_me_app
DB_MIGRATOR_PASSWORD=change_me_migrator
DATABASE_URL=postgresql+pg8000://app:change_me_app@postgres:5432/sygna
MIGRATION_DATABASE_URL=postgresql+pg8000://migrator:change_me_migrator@postgres:5432/sygna
# ── Storage ──────────────────────────────────────────────────────────────────
DATA_DIR=/data
# ── Auth / sessions ──────────────────────────────────────────────────────────
SESSION_TTL_HOURS=12
LOGIN_MAX_ATTEMPTS=5
LOGIN_LOCKOUT_MINUTES=15
# Empty = auto-detect from the request scheme (Secure over HTTPS only). Never key
# this off APP_ENV — a Secure cookie over plain HTTP is dropped and login "doesn't stick".
SESSION_COOKIE_SECURE=
# CORS — empty by default (same-origin design). Comma-separated origins for a
# separately-served console in dev, e.g. http://localhost:8041
CORS_ALLOW_ORIGINS=
# ── Bootstrap admin (seed) ───────────────────────────────────────────────────
BOOTSTRAP_ADMIN_EMAIL=admin@example.com
BOOTSTRAP_ADMIN_PASSWORD=admin12345
# Seed a small demo firm so the app isn't empty on first run.
SEED_DEMO=true
# ── Reminders ────────────────────────────────────────────────────────────────
# The scheduler is an in-process asyncio task. In a multi-instance deploy run it on ONE
# instance only and set false on the others — duplicate runs are harmless (every reminder is
# deduplicated by a database constraint) but they are wasted work.
REMINDERS_ENABLED=true
REMINDER_INTERVAL_HOURS=6
# ── Galena (the document store) ──────────────────────────────────────────────
# Stage A: Sygna calls Galena's REST API as the acting user, so Galena's authz stays
# the single authority on document access. Empty base URL → the integration is a
# no-op and matters are created without a case file (the UI says so).
GALENA_BASE_URL=
# The console links here when a user opens a matter's case file. Defaults to
# GALENA_BASE_URL when empty.
GALENA_CONSOLE_URL=
# Where new case-file projects are created in Galena's tree (a node id). Empty →
# Sygna asks Galena for the acting user's personal workspace.
GALENA_CASEFILE_PARENT_ID=
GALENA_TIMEOUT_SECONDS=15
# Stage C — render the case file INSIDE Sygna's matter screen rather than behind a link.
# Needs three things, all of them, or you get a blank frame:
# 1. this flag true, and GALENA_CONSOLE_URL set;
# 2. both apps under one parent domain (e.g. sygna.kancelaria.pl + galena.kancelaria.pl)
# with Galena's session cookie scoped to `.kancelaria.pl`, so the frame is authenticated;
# 3. a matching change in GALENA: its console CSP must widen `frame-ancestors 'none'` to
# allow Sygna's origin (see PLAN.md §3.4 — that change belongs in the Galena repo).
# Leave false until 2 and 3 are done. The console falls back to a link and says why.
GALENA_EMBED=false
# ── Reverse proxy ────────────────────────────────────────────────────────────
# Plain HTTP on :80 by default. Set to your domain for automatic TLS.
CADDY_SITE_ADDRESS=:80
# ── OpenTelemetry (opt-in) ───────────────────────────────────────────────────
OTEL_ENABLED=false
OTEL_SERVICE_NAME=sygna-backend
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
+5
View File
@@ -0,0 +1,5 @@
* text=auto eol=lf
*.png binary
*.jpg binary
*.gif binary
*.ico binary
+58
View File
@@ -0,0 +1,58 @@
name: CI
on: [push, pull_request]
jobs:
backend:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_DB: sygna
POSTGRES_PASSWORD: superpw
ports: ["5432:5432"]
options: >-
--health-cmd "pg_isready -U postgres" --health-interval 5s
--health-timeout 5s --health-retries 20
env:
DATABASE_URL: postgresql+pg8000://app:apppw@localhost:5432/sygna
MIGRATION_DATABASE_URL: postgresql+pg8000://migrator:migpw@localhost:5432/sygna
DATA_DIR: ${{ github.workspace }}/sygna-data
BOOTSTRAP_ADMIN_EMAIL: admin@example.com
BOOTSTRAP_ADMIN_PASSWORD: adminpass1
SEED_DEMO: "true"
SYGNA_RUN_INTEGRATION: "1"
steps:
- uses: actions/checkout@v5
- uses: actions/setup-python@v6
with: { python-version: "3.12" }
- name: Create least-privilege roles
run: |
PGPASSWORD=superpw psql -h localhost -U postgres -d sygna -v ON_ERROR_STOP=1 <<'SQL'
CREATE ROLE migrator LOGIN PASSWORD 'migpw';
CREATE ROLE app LOGIN PASSWORD 'apppw';
GRANT CONNECT ON DATABASE sygna TO migrator, app;
ALTER SCHEMA public OWNER TO migrator;
GRANT USAGE ON SCHEMA public TO app;
-- Pre-create the extension as the superuser; the migration's CREATE EXTENSION IF NOT
-- EXISTS then no-ops, so the least-privilege migrator never needs extension rights.
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
SQL
- name: Install deps
working-directory: backend
run: pip install -r requirements-dev.txt
- name: Migrate + seed
working-directory: backend
run: alembic upgrade head && python -m app.seed
- name: Tests
working-directory: backend
run: pytest -q --cov=app --cov-report=term-missing
- name: License gate (Python)
working-directory: backend
run: python scripts/license_gate.py
- name: Shared-file drift vs Galena
working-directory: backend
# Skips cleanly when Galena is not checked out (which is the normal CI case today).
# Point GALENA_REPO at a checkout — or add a second actions/checkout step for the
# Galena repository — to make this gate real.
run: python scripts/shared_check.py
+20
View File
@@ -0,0 +1,20 @@
# Secrets / config
.env
.env.*
!.env.example
# Local editor / agent config + scratch
.claude/
*.log
# Python
__pycache__/
*.py[cod]
.venv/
*.egg-info/
.pytest_cache/
.coverage
# Local data
/data/
backend/data/
+258
View File
@@ -0,0 +1,258 @@
# CLAUDE.md
Guidance for Claude Code when working in this repository.
## What this is
**Sygna** — practice management (CRM + matters + time) for **Polish law firms**. Sibling
application to **[Galena](../Galena)**, deliberately built on the same stack so the two can merge
into one shared system. Stack: **FastAPI + SQLAlchemy 2 + Alembic + PostgreSQL 16**, Argon2id
auth + server-side cookie sessions, a **no-build static console** (vanilla JS), Docker Compose +
Caddy. License **Apache-2.0**; every dependency is permissive (no copyleft).
Sygna owns *matters, people, time and money*. Galena owns *documents and their history*. Neither
duplicates the other: a matter's case file (`akta sprawy`) is a Galena project, referenced by
`matter.document_node_id`.
Read [`PLAN.md`](PLAN.md) before any substantial change — it holds the compatibility contract
with Galena, the roadmap, and why things are the way they are.
[`SHARED.md`](SHARED.md) lists the files copied from Galena that must stay diff-clean.
## Where things live
```
backend/app/
main.py config.py db.py deps.py errors.py security.py enums.py schemas.py seed.py
observability.py logging_config.py
models/ identity · node (copied from Galena — see SHARED.md)
party (+alias, link) · matter (+matter_party, ethical_wall)
conflict (conflict_check, lead) · correspondence · deadline (+court_event)
timelog · notification (+prefs)
billing (expense, invoice, invoice_line, client_deposit, deposit_movement)
rate (rate_card, rate_card_entry, lawyer_profile)
services/ auth · authz (Galena's resolver + ethical walls) · nodes · audit · settings
parties (name normalisation) · conflicts (the engine) · matters
correspondence (the inbox + service dates) · deadlines · timelog · leads · stats
billing (disbursements, invoices, client money) · reports (realisation,
utilisation, profitability, lock-up, aged debt) · workdays (PL holidays, pure)
fees (pure: opłaty sądowe + koszty zastępstwa) · rates (resolution)
registers (pure mapping of KRS / Biała lista payloads)
notify (idempotent push) · reminders (the engine + lifespan scheduler)
integrations/ base (retries, UpstreamError) · galena · registers (KRS, Biała lista)
[e-Doręczenia/KSeF: Phase 2]
routers/ health auth users admin nodes permissions parties conflicts intake
matters deadlines correspondence timelog billing reports fees rates
registers notifications dashboard
tests/fixtures/krs_odpis_aktualny.json trimmed real KRS response — the mapper's test input
alembic/ env + 0001_initial (pgcrypto, enums, create_all, least-privilege grants)
frontend/ index.html · app.css · app.js (no build step, PL-first)
Tabler icons vendored into app.js's ICN map (CREDITS.md)
db/init/ 01-roles.sh (creates the app + migrator roles)
docker-compose.yml · Caddyfile · .env.example · .github/workflows/ci.yml
docs/CRMecenas-Discovery-Report.md (research; §4 superseded by PLAN.md)
```
## Commands
```bash
docker compose up -d --build # full stack: postgres -> migrate(+seed) -> backend -> caddy
cd backend && pytest # DB-free unit tests; integration auto-skips
SYGNA_RUN_INTEGRATION=1 pytest # full API loop (needs a migrated+seeded Postgres)
python scripts/license_gate.py # CI license gate locally
```
## Invariants — preserve these
- **Polish vernacular UI, English internals.** The UI says Sprawa / Klient / Termin / Karta
czasu pracy / Konflikt interesów; code, routes and tables stay English. The mapping is in
PLAN.md §7 — keep it consistent across console and docs.
- **Strict layering:** routers → services → models. Routers never build SQL — no
`select(...)` / `db.add` / `db.execute` in a router. A lone `db.get(Model, id)` by primary key
is acceptable. Services own every domain rule.
- **`services/authz.py` is the only access authority.** Routers call `assert_can_read` /
`assert_role` before every read and write. **No access → 404, never 403** — the existence of a
matter is itself privileged.
- **Ethical walls beat everything.** A `deny` in `ethical_wall` removes every role on that
matter, including owner, manager and instance admin. Walls are administered from **outside**
the barrier: `matters.assert_wall_admin` authorizes against the matter's *parent* container,
because authorizing it on the matter itself lets anyone lock themselves out permanently.
- **A matter is a leaf of the node tree**, mirroring Galena's project rule. `nodes.LEAF_KINDS`
is the one definition. Sygna never creates a node of kind `project` — those belong to Galena.
Matter nodes are created only by `services/matters.open_matter`, never by the nodes router: a
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.
- **`conflict_check` rows are evidence.** Never edited after a decision (`conflicts.decide`
refuses a second one) and never deleted — the `app` DB role has no DELETE on that table.
To change an outcome, run a new check.
- **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.
- **`legal_service_date` is set once, from the source system, never inferred.** It lives on
`correspondence` and is the only thing a procedural deadline may count from — `received_at` is
the separate, operational fact of when the row appeared here, and nothing counts from it.
Correcting a service date is refused once a deadline derives from it (moving one date that six
deadlines were computed from is how a firm misses all six); delete those deadlines first, on
purpose. Every derived deadline records how its date was reached in words (`deadline.basis`)
and points back at the row via `source_correspondence_id`, **`ondelete=RESTRICT`** — a deadline
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.
- **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
`(channel, external_ref)` — a partial unique index, so a re-poll cannot duplicate an item even
under a race, and hand-entered items with no upstream id are unconstrained.
- **Dual control on deadlines.** `deadlines.confirm` refuses the creator for `statute` and
`court` sources. A four-eyes check performed by one pair of eyes is theatre.
- **All external I/O goes through `app/integrations/`**, via `integrations.base.request`, and
raises only `UpstreamError`. No `httpx` call anywhere else in the codebase. A connector
failure must never break the primary action — see `galena.try_create_case_file`.
- **Money in integer minor units (grosze), time in integer minutes.** No float near an invoice.
`TimeEntry.amount_minor` is the single definition of how time becomes money; time rounds **up**
to 6-minute units, and the amount rounds **down**, in the client's favour. The console converts
złote↔grosze at the input box (`zlToMinor`/`minorToZl`) and nowhere else.
- **An issued invoice is immutable.** `issued` is the point of no return: the correction is a
credit note (`faktura korygująca`), never an edit. A credit note mirrors every line with the
sign flipped and **releases the underlying time and expenses back to unbilled**, so a mistake
is re-billed properly rather than silently written off. One credit note per invoice.
- **An invoice number is assigned at issue, never at draft** — a gap in the sequence is a
question from the tax office. Derived from the highest existing number, so a restored backup
cannot hand the same one out twice.
- **Approval is a separate act from issuing.** `approved_by_id` records who read the narratives
the client is about to read; that review is why firms bill late and correctly.
- **VAT is summed per line, never taxed on the total** — three lines of 3,33 give 2,31, not
2,30. Pass-through disbursements (opłata sądowa, skarbowa) go on at 0%: recharged at cost,
they are not our supply. **The VAT treatment of disbursements needs an accountant's sign-off**
— the same caveat as the fee schedules.
- **Client money can never go negative.** `client_deposit.balance_minor` carries a CHECK
constraint, so a bug in `services/billing.py` cannot overdraw a client's funds.
- **Money is an approver's business.** Recording time is `editor`; deciding what a client is
asked to pay is `approver` (`billing.assert_can_bill`).
- **Every report states its basis, and is filtered to what the reader may see.** *Standard* is
before write-offs; *billed* means it reached an **issued** invoice (a draft is not billed, a
cancelled one released its work); *collection* is net of VAT, because VAT is not revenue.
`reports.visible_matters` runs the same authz resolver as everything else — a management
report that quietly includes a walled matter is a leak wearing a spreadsheet.
- **Utilisation counts real Polish working days** (`services/workdays.py`, pure and tested,
Easter via the anonymous Gregorian algorithm). Treating Christmas as available flatters
everyone by a few per cent. `next_working_day` is there for art. 115 k.c. when Phase 2 has a
real service date to count from.
- **Profitability without a cost rate reports `incomplete`, never a flattering zero.**
`lawyer_profile.cost_rate_minor` is the input; a matter with any uncosted time is flagged in
the API and badged in the console.
- **`services/fees.py` holds legal data with a shelf life.** The fee schedules are plain data
with the statute on every bracket, so a lawyer can check the table without reading Python.
Every response carries `schedule_version`, `sources` and `verify_note`, and the UI shows them
— a calculator that looks authoritative and is out of date is worse than one that admits it.
Court fees round **up** to a whole złoty because art. 21 u.k.s.c. says so, applied to the
payable amount after any fraction, not just the base.
- **A rate is resolved, and the resolution explains itself.** `rates.resolve` walks
matter override → matter card → client card → firm card → house setting, and within a card
person → grade → fallback, returning both the rate and a human-readable source. It resolves
for the date of the WORK, not today. `TimeEntry.rate_minor` is a snapshot, so editing a card
never re-prices recorded time. When nothing matches the answer is an explicit "no rate", never
a silent zero.
- **Every reminder is idempotent by construction.** `notify.push` enforces uniqueness on
`(recipient_id, dedupe_key)` with a database constraint, not a SELECT-then-INSERT, and every
reminder names its milestone (`deadline:<id>:d7`). That is what makes the scheduler safe to
run as often as it likes, and `POST /admin/reminders/run` safe to press. **Never add a
reminder without a dedupe key** — the scheduler re-derives the same set every cycle.
- **Reminders escalate, they do not nag.** Milestones are sparse (14/7/3/1/0 days); an overdue
deadline is announced once, then once more after three days to whoever manages the matter —
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.
- **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
it. **Never create a `party` or `party_link` from a masked name** — a fake party in the
register that decides whether the firm may take a case is the worst possible place to guess.
The console tells the user to type the names in by hand.
- **A register fills blanks, it does not overwrite.** `registers.party_updates` defaults to
filling only empty fields: the firm may have deliberately recorded a correspondence address or
a trading name, and silently replacing it throws away work someone did on purpose. Overwriting
is available but has to be asked for.
- **Register mapping is pure and tested against a captured real response**
(`tests/fixtures/krs_odpis_aktualny.json`). The HTTP lives in `integrations/registers.py`, so
the mapping never depends on a live government service to be tested.
- **Seniority lives on `lawyer_profile`, not `app_user`.** `app_user` is byte-identical with
Galena's and adding a column there would break the Stage B merge (SHARED.md).
- **`matters.CLEARABLE_FIELDS` is the list of fields a user may blank out.** Everywhere else
`None` means "not supplied". Without it, setting a rate override would be a one-way door.
- **Files shared with Galena stay diff-clean** (SHARED.md). Change both repositories in the same
commit, or Stage B stops being a data move and becomes a rewrite.
- **Core stays permissive.** Apache-2.0; CI denies GPL/AGPL/SSPL. Copyleft or heavyweight
components are optional sidecars, never core.
- **No build step for the console.** The one permitted exception is a committed Vite bundle with
a working fallback, following Galena's `frontend/static/editor.js` precedent.
- **Console security:** `esc()` every dynamic value; bearer token in memory only, cookie session
primary; nothing loads from a CDN (the CSP has no third-party origins). `frame-src` names
Galena's origin only when `GALENA_EMBED` is on.
- **Icons are Tabler (MIT), path data vendored into the `ICN` map** — the same family Galena
uses, so the two consoles match in a shared launcher. Never load them from a CDN; see
CREDITS.md for the list.
- **Brand = Open Color `cyan8` #0c8599** (`cyan4` #3bc9db in dark, where cyan8 is too dim for
stroke-weight use). It is confined to **identity, not controls**: the app mark, icon tiles
(`.appcard .ai`), the avatar, the focus ring. Buttons, nav and toolbar glyphs stay monochrome
— brand everything and nothing stands out. Semantic ok/warn/err is a separate axis. This is a
deliberate divergence from Galena, whose brand colour touches the app icon only.
- **Mobile: the top bar keeps four controls** (menu, breadcrumb, record-time, notifications,
account). Everything else carries `.js-tool` and moves into the account sheet below 880px —
nine 30px buttons left the breadcrumb exactly 0 pixels wide. A horizontally scrolling `body`
is the one layout bug with no acceptable version; wide tables scroll inside `.tablewrap`.
- **Never transition `visibility` over a duration or with a delay.** The off-canvas drawer needs
the transition machinery to tick, and when frames are throttled it gets stuck in whichever
state it was in. `transform` transitions; `visibility` flips instantly.
## Gotchas
- On Windows, write `.env` **without a BOM** (PowerShell `Out-File -Encoding utf8` adds one, and
pydantic-settings folds it into the first key name) — use
`[System.IO.File]::WriteAllText(...)`.
- The migration creates enum types explicitly, then runs `Base.metadata.create_all` (enums use
`create_type=False`). **Adding a model needs no migration change**; adding an **enum** does —
put it in the `ENUMS` map in `0001_initial.py`.
- `NodeKind` keeps Galena's `project` label even though Sygna never writes it, so a Stage B
merge into one `core` schema needs no type surgery.
- Polish name matching lives in `services/parties.py` (`normalize` / `_stem` / `similarity`).
`_stem` is a deliberate approximation — it over-matches, which is the right failure direction
for a conflict screen. Replacing it with Morfologik (BSD) is the documented upgrade; nothing
else depends on how it works. `similarity` is **containment, not Jaccard**, so "Kowalski"
scores 1.0 against "Kowalski Nowak i Wspólnicy" — acting against one named partner of a firm
we act for is exactly the conflict being looked for.
- `models/timelog.py` (not `time.py`) so the module never shadows the stdlib.
## Status
Stage A / Phase 1 complete, plus the **correspondence spine**, the **court-fee calculator**,
**rate cards**, the **registers connector**, the **reminder engine** and **Phase 3 — money,
complete** (August 2026). Verified against a real PostgreSQL 16: migration + seed, **209 tests**
(127 DB-free + 82 integration) passing twice in a row, **126 routes, 29 tables**, the
least-privilege grants (`app` cannot mutate `audit_log` or delete `conflict_check`), the licence
gate, `scripts/shared_check.py` clean against Galena, and every console route rendering with no
JS errors. The KRS and Biała lista connectors were exercised against the **live** government
services on 2026-08-13.
`practice_mode` (`law_firm` | `in_house`) is an instance setting: an in-house department gets
the same matters, deadlines and conflicts without the billing surface. `GET /config` carries it
to the console.
The reminder scheduler is an in-process asyncio task in the app lifespan (Galena's backup
-scheduler pattern). In a multi-instance deploy, run it on one instance only —
`REMINDERS_ENABLED=false` on the others. Duplicate runs are harmless (the dedupe constraint),
but they are wasted work.
**The fee schedules in `services/fees.py` have not been checked against an official text.** They
were assembled from working knowledge of the statutes. The arithmetic is tested; the numbers
need a lawyer's eye before anyone relies on them, and the UI says so on every result.
Galena integration is implemented and **untested against a live Galena** — no instance was
available; `GALENA_BASE_URL` empty is a clean no-op.
There is only one migration. `0001_initial` was extended in place with the `correspondence`
table and its enums rather than adding `0002`, because nothing is deployed — the `create_all`
-from-metadata style means a table added to the model would otherwise be created twice. Once
this ships anywhere, that stops being an option and new tables need their own revision.
+51
View File
@@ -0,0 +1,51 @@
# Credits
Sygna is Apache-2.0. Every dependency and vendored asset is permissively licensed — the CI gate
(`backend/scripts/license_gate.py`) fails the build on GPL, AGPL or SSPL.
## Vendored assets
| Asset | Licence | Where | Note |
|---|---|---|---|
| [Tabler Icons](https://tabler.io/icons) | MIT | `frontend/app.js` (`ICN` map) | Outline set. Path data copied verbatim from the official SVGs; nothing is fetched from a CDN, which is what the console's CSP requires. The same family Galena vendors, so the two consoles read as one product in a shared launcher. |
Icons in use, by their Tabler names: `layout-dashboard`, `briefcase`, `heart-handshake`, `clock`,
`alert-triangle`, `inbox`, `shield-check`, `settings`, `plus`, `check`, `x`, `file-text`,
`folder-open`, `sun`, `moon`, `device-desktop`, `eye`, `eye-off`, `external-link`, `trash`,
`menu-3`, `search`, `bell`, `calculator`, `apps`, `users`, `license`.
## Palette
[Open Color](https://yeun.github.io/open-color/) by Heeyeun Jeong — MIT. Sygna's brand is
**cyan8 `#0c8599`** (cyan4 `#3bc9db` in dark mode); chart series use violet/cyan/orange from the
same palette. Only the hex values are used, not the stylesheet.
## Runtime dependencies
| Package | Licence |
|---|---|
| FastAPI, Starlette | MIT |
| Uvicorn | BSD-3-Clause |
| Pydantic, pydantic-settings | MIT |
| SQLAlchemy | MIT |
| Alembic | MIT |
| pg8000 | BSD-3-Clause |
| argon2-cffi | MIT |
| httpx | BSD-3-Clause |
| OpenTelemetry SDK + instrumentation | Apache-2.0 |
| PostgreSQL | PostgreSQL Licence |
| Caddy | Apache-2.0 |
## Data sources
The console displays results computed from, or fetched from, the following. None of them are
redistributed with the software.
- **KRS** — `api-krs.ms.gov.pl`, Ministerstwo Sprawiedliwości. Public register data.
`backend/tests/fixtures/krs_odpis_aktualny.json` is a trimmed capture of one public company
record, kept so the mapper can be tested without calling a government service.
- **Wykaz podatników VAT ("Biała lista")** — `wl-api.mf.gov.pl`, Ministerstwo Finansów.
- **Fee schedules** in `backend/app/services/fees.py` are transcriptions of statutory tables
(u.k.s.c. and the 2015 rozporządzenia on advocates' and legal advisers' fees). Statutes are not
subject to copyright in Poland; the transcription still needs a lawyer's verification before
anyone relies on the numbers, which the UI states on every result.
+53
View File
@@ -0,0 +1,53 @@
# Caddy serves the static console and reverse-proxies the API to the backend.
# Default: plain HTTP on :80. For TLS, set CADDY_SITE_ADDRESS to your domain in .env
# (Caddy then provisions a certificate automatically).
#
# ── Stage C: one shell over Sygna and Galena (PLAN.md §3.4) ───────────────────
# Put both applications under ONE PARENT DOMAIN so the launcher, the deep links and the
# embedded case file behave like a single product:
#
# CADDY_SITE_ADDRESS=sygna.kancelaria.pl # this file
# galena.kancelaria.pl { ... } # Galena's own Caddyfile
#
# Two things then have to be true, and neither is in this file:
#
# 1. Galena's session cookie must be scoped to `.kancelaria.pl` rather than its own host,
# or the embedded frame loads unauthenticated.
# 2. Galena's console CSP must widen `frame-ancestors 'none'` to name Sygna's origin.
# That is a one-line change in the GALENA repository — it cannot be done from here, and
# without it the browser silently refuses to render the frame.
#
# Until both land, leave GALENA_EMBED=false: Sygna links to the case file instead, and says so.
# Same-origin path mounting (both apps on one host under /sygna and /galena) was considered and
# rejected — both consoles assume root-relative asset and API paths, so it is a rewrite of two
# frontends to save one DNS record.
{$CADDY_SITE_ADDRESS::80} {
encode gzip
# API + health → backend
@api path /api/v1/* /healthz
handle @api {
reverse_proxy backend:8000
}
# Everything else → the static console (SPA fallback to index.html)
handle {
root * /srv
try_files {path} /index.html
# Revalidate the console assets (ETag) so a rebuilt app.js/app.css is picked up
# without a manual hard refresh.
header Cache-Control "no-cache"
# Content-Security-Policy for the console. 'unsafe-inline' covers the theme
# pre-paint inline script + inline style attributes. No third-party origins:
# Sygna's console loads nothing from a CDN.
header Content-Security-Policy "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; img-src 'self' data: blob:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'"
file_server
}
header {
X-Content-Type-Options nosniff
X-Frame-Options DENY
Referrer-Policy strict-origin-when-cross-origin
Cross-Origin-Opener-Policy same-origin
}
}
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or Derivative
Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and do
not modify the License. You may add Your own attribution notices
within Derivative Works that You distribute, alongside or as an
addendum to the NOTICE text from the Work, provided that such
additional attribution notices cannot be construed as modifying
the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 The Sygna Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+573
View File
@@ -0,0 +1,573 @@
# Sygna — Build Plan
**Sygna** — a practice-management system (CRM + matters + time + billing) for Polish law firms.
Sibling application to **Galena**; designed from day one to merge into one shared system with it.
- **License:** Apache-2.0 (same as Galena). Permissive-only dependency policy, enforced in CI.
- **Stack:** identical to Galena — FastAPI + SQLAlchemy 2 + Alembic + PostgreSQL 16, Argon2id +
server-side cookie sessions, a no-build static console (vanilla JS), Docker Compose + Caddy.
- **Supersedes:** §4 of [`docs/CRMecenas-Discovery-Report.md`](docs/CRMecenas-Discovery-Report.md).
The discovery report's requirements analysis (§3) still stands; its *technology* recommendation
(Atomic CRM / react-admin / Supabase) is withdrawn — see §1.2.
---
## 1. Requirements analysis
### 1.1 What was asked
| # | Requirement | Resolution |
|---|---|---|
| 1 | Name it **Sygna** | Locked. From `sygnatura akt` — the case reference number, which is literally the primary key of a legal matter. §1.4 covers the brand surface. |
| 2 | Use the **same tech stack as Galena** | Locked. §2 pins it version-for-version. |
| 3 | Make it **compatible with Galena** for a future shared system | This is the design driver, not a footnote. §3 is the compatibility contract; it changes the data model, the auth model and the UI shell. |
| 4 | Produce **PLAN.md** | This document. |
| — | **License: Apache-2.0** | Locked. `LICENSE` written. CI gate denies GPL/AGPL/SSPL, matching Galena's policy. |
### 1.2 What this changes versus the discovery report
The report recommended forking Atomic CRM (MIT, React + Supabase). Requirement 2 overrides that — and
on inspection the override is an improvement, not a compromise:
- **Galena already is the better starting point.** It is Apache-2.0, already ours, and already
implements the half of a legal system that is expensive to build: versioned document storage, a
review/approval workflow, encryption, an audit log, a permission tree with inheritance, an in-browser
document viewer (PDF/DOCX/scans), OCR, and side-by-side comparison with authorship. In legal terms
that is the **case file** (`akta sprawy`) — done.
- **What Sygna adds is what Galena deliberately does not do:** clients, matters, parties, conflicts,
deadlines, time, money, and the Polish statutory integrations.
- **Two dependencies from the report are dropped.** Mayan EDMS (document management) is unnecessary —
Galena is the DMS. **docassemble** (MIT, document assembly) is deferred from v1: it is an entire
second stack (its own Python app, Redis, Celery, Apache) and would violate requirement 2. Document
generation in v1 is `python-docx` (already a Galena dependency) + a template merge with Polish
declension; docassemble stays a documented optional sidecar for v3.
- **The frontend constraint is real and accepted.** No React, no TypeScript, no build step for the
console. Galena proves this scales further than it sounds — its `app.js` already carries an editable
CSV grid, a commit-graph renderer, a diff viewer and a full i18n layer. Where a component genuinely
needs a build (a month-view calendar), Sygna follows Galena's `frontend/static/editor.js` precedent:
a Vite bundle **built separately and committed as a static artifact**, with a working fallback if it
is absent.
### 1.3 The three things that make this a vertical product
Everything else is table stakes. These are the reasons a firm buys Sygna instead of a generic CRM, and
they get the architectural attention:
1. **Conflict of interest checking** — a blocking gate at intake, fuzzy across Polish declension and
diacritics, searching clients, former clients, opposing parties and related entities, producing a
permanent decision record. Professional-liability grade.
2. **The deadline engine** — `terminy` computed from a legally binding service date, with dual
confirmation and escalating reminders. A missed `termin zawity` is malpractice.
3. **The Polish statutory integrations** — e-Doręczenia, Portal Informacyjny, KSeF. Dated, mandatory,
and effectively impossible for an international vendor to ship quickly.
### 1.4 Brand surface
Following Galena's invariant — **UI chrome is monochrome; the brand colour appears only on the app
icon** (Galena: Open Color `violet8` #5f3dc4 on `violet0`).
- **Sygna's mark:** Open Color **`cyan8` #0c8599** rounded square, glyph in **`cyan0` #e3fafc** —
visually distinct from Galena's violet at launcher size, which matters once both apps sit in one
shell. Glyph: a section mark / reference-number motif rather than a scales-of-justice cliché.
*(An earlier draft of this file called #0b7285 "teal8". It is actually `cyan9`; real `teal8` is
#099268. The palette is cyan throughout.)*
- **Where the brand appears:** the app mark, icon tiles, the avatar and the focus ring — things
that read as an identity. Buttons, nav and toolbar glyphs stay monochrome; a console where
everything is branded has nothing that stands out.
- **Chart colours** reuse Galena's `--chart-1/2/3` tokens verbatim (violet/teal/orange, per-theme).
- **Wordmark:** "Sygna". Tagline: *system zarządzania kancelarią*.
- **Not yet done:** `.pl`/`.com` domain and UPRP/EUIPO clearance for "Sygna". Do this before any
public branding; the name is otherwise unverified.
---
## 2. Stack — pinned to Galena
Identical choices, identical versions, so a future merge has no dependency reconciliation.
### Backend
```
Python 3.12+ ruff, line-length 100, target py312
fastapi==0.115.6 API_PREFIX = "/api/v1"; docs at /api/v1/docs
uvicorn[standard]==0.34.0
python-multipart==0.0.20 multipart uploads
pydantic==2.10.4 + pydantic-settings==2.7.1 (typed Settings from .env)
SQLAlchemy==2.0.50 Mapped[]/mapped_column style, DeclarativeBase
alembic==1.14.0
pg8000==1.31.2 pure-Python PostgreSQL driver, BSD-3 (no libpq, no LGPL)
argon2-cffi==23.1.0 Argon2id password hashing
cryptography==44.0.0 AES-256-GCM, if/when Sygna stores secrets at rest
```
**New dependencies Sygna needs** (all permissive, all pass the gate):
```
httpx BSD-3 — the one outbound HTTP client, for every government API
signxml Apache-2.0 — XAdES signing for KSeF (verify against KSeF 2.0 spec)
pyHanko MIT — PAdES signing/verification for PDF pleadings (Phase 4)
python-docx==1.1.2 MIT — already a Galena dep; template merge for document generation
Pillow==11.1.0 HPND — already a Galena dep; if Sygna renders anything
```
Deliberately **not** added: Celery/Redis (use an asyncio task in the app `lifespan`, exactly as
Galena's backup scheduler), an ORM-adjacent admin framework, any Node backend.
### Frontend
Vanilla JS, no build. `index.html` + `app.css` + `app.js`, hash router, the `api()`/`esc()`/`toast()`
helpers, the `ICN` icon map, the theme pre-paint inline script, EN/PL i18n by English-source-text
matching (`I18N.pl` + `_tr`/`_trAttr`/`localize`, covering `title` and `placeholder` attributes).
Sygna is **PL-first**, so the English source strings must be short and stable, and PL coverage is a
merge requirement, not a follow-up.
### Infrastructure
```
docker-compose.yml postgres:16 → migrate(+seed) → backend → caddy:2 (only Caddy published)
db/init/01-roles.sh creates the least-privilege `app` and `migrator` roles
Caddyfile TLS + static console + reverse proxy to the backend
.github/workflows pytest (+ coverage) on a Postgres service, then scripts/license_gate.py
```
Dev ports (offset from Galena's 8012/8014/8021 so both can run side by side):
`.claude/launch.json` → **sygna** 8032, **sygna-db** 8034, **sygna-static** 8041.
Env prefix `SYGNA_*` (`SYGNA_FRONTEND_DIR`, `SYGNA_RUN_INTEGRATION`); unprefixed `DATABASE_URL` /
`MIGRATION_DATABASE_URL` / `DATA_DIR` as in Galena.
---
## 3. Compatibility contract with Galena
The goal: **one system, two applications, one identity, one permission tree, one design language.**
Sygna is the system of record for *matters, people, time and money*; Galena is the system of record
for *documents and their history*. Neither duplicates the other.
### 3.1 The central mapping
> **A matter is to Sygna what a project is to Galena.**
Galena's org tree is `workspace → group/folder → project`, where a **project is a leaf** and its
contents live in git. Sygna reuses that tree *verbatim* — same `node` table, same `permission_grant`,
same materialized `path`, same `authz` resolver — and adds `matter` as a second leaf kind.
Each matter owns a Galena project as its case file:
```
matter.document_node_id → node.id (kind = 'project')
```
The project is created automatically when a matter is opened, as a **sibling** of the matter node
under the same parent container. Consequences:
- Galena's invariant "a project is a leaf; nothing nests inside it" is **untouched** — no change to
Galena is required to make this work.
- A single `permission_grant` on the parent container covers both the matter data and its documents,
so access stays coherent without a second permission system.
- Opening `Sprawa → Akta` deep-links to Galena at `#/n/<document_node_id>` (Stage A) or embeds
Galena's ReaderJS viewer same-origin (Stage C).
*Alternative considered:* relaxing Galena's leaf rule so a project can nest inside a matter node.
Cleaner conceptually, but it edits Galena's most load-bearing invariant to buy nothing. Rejected.
### 3.2 What is copied verbatim (byte-identical shape, not "similar")
These must stay diff-clean against Galena so that Stage B is a data move, not a rewrite:
| Asset | Galena source | Rule |
|---|---|---|
| `models/base.py` | `NAMING_CONVENTION`, `Base`, `UUIDPkMixin` (`gen_random_uuid()`), `TimestampMixin` | Copy unchanged. UUID PKs mean IDs are globally unique across both databases — a prerequisite for merging. |
| `models/identity.py` | `AppUser`, `Session`, `AppSetting`, `AuditLog` | Copy unchanged, including `uq_app_user_email_lower`, the nullable `password_hash` (SSO seam) and the append-only audit shape. |
| `models/node.py` | `Node`, `PermissionGrant`, `Favorite` | Copy unchanged; only `NodeKind` gains a member. |
| `services/authz.py` | effective-role resolver + grant CRUD | Copy unchanged. Extended only by the ethical-wall deny check (§4.2). |
| `errors.py` | RFC 9457 Problem Details, the `AppError` hierarchy, the middleware ordering | Copy unchanged. Both apps' clients parse one error format. |
| `deps.py` | bearer-over-cookie token extraction, `get_current_user`, `require_admin` | Copy; cookie name becomes `sygna_session`. |
| `db.py`, `config.py` shape | engine with `hide_parameters=True`, `lru_cache`d `Settings` | Copy; extend settings, don't restructure. |
| `scripts/license_gate.py` | dependency licence gate | Copy unchanged. |
| Console shell | `api()`, `esc()`, `toast()`, `ICN`, theme handling, `_tr`/`localize`, `app.css` tokens | Copy. Sygna's screens are new; the shell is shared. |
**Divergence rule:** if a shared file must change, change it in **both** repos in the same commit and
note it in a `SHARED.md` sync list. Do not fork behaviour silently.
### 3.3 Enum compatibility
`NodeRole` (`viewer < editor < approver < manager`) is reused **unchanged** — the ranking maps onto
legal practice cleanly:
| Role | In Sygna |
|---|---|
| `viewer` | read the matter and its file; no time entry |
| `editor` | record time, add parties, draft documents, create deadlines |
| `approver` | approve invoices, sign off conflict checks, publish pleadings |
| `manager` | manage access on this node and below |
`NodeKind` gains one member: `matter`. `PrincipalType`, `ReviewPolicy`, `EncryptionMode` are reused
as-is. Every Sygna-specific enum (§4.1) is a new native PG enum, mirrored as a `StrEnum`, registered
in the migration's `ENUMS` map — same pattern, no collisions with Galena's names.
### 3.4 Staged convergence
**Stage A — separate, shaped-alike (v1, now).**
Own repo, own database `sygna`, own `sygna_session` cookie. Identity tables have the identical shape
but are populated independently. `matter.document_node_id` is a plain UUID column with no cross-DB FK;
Sygna calls Galena's REST API to create and read the project. Users exist twice; that is accepted and
temporary.
**Stage B — shared identity and tree.**
One PostgreSQL cluster, three schemas: **`core`** (`app_user`, `session`, `app_setting`, `audit_log`,
`node`, `permission_grant`, `favorite`), **`galena`**, **`sygna`**. `core` is owned by a single
migration lineage (Galena's, since it is the incumbent); each app migrates only its own schema.
Because Galena's sessions are already DB-backed with hashed tokens, a shared `core.session` plus a
cookie scoped to the parent domain gives **real SSO with no new protocol** — no OIDC provider needed.
`document_node_id` becomes a genuine FK.
**Stage C — one shell.** *(Sygna's half built; two Galena changes outstanding.)*
Built here: a **launcher** (`GET /shell`) listing the applications in the firm's system, an **Akta
tab** on the matter screen that renders the case file in an iframe, the **Tabler icon set** shared
with Galena so the two consoles read as one product, and a `frame-src` that names Galena's origin
when `GALENA_EMBED=true`.
**Correction to the original plan: this cannot work "same-origin".** Galena's console sends
`frame-ancestors 'none'`, and its session cookie is scoped to its own host — so a Sygna served from
a different origin gets a blank, unauthenticated frame. Path-mounting both apps on one host was
considered and rejected: both consoles assume root-relative asset and API paths, so it is a rewrite
of two frontends to save one DNS record.
The workable shape is **two subdomains of one parent** (`sygna.kancelaria.pl`,
`galena.kancelaria.pl`) plus two changes **in the Galena repository**:
1. scope Galena's session cookie to `.kancelaria.pl` rather than its own host;
2. widen its console CSP `frame-ancestors 'none'` to name Sygna's origin.
Until both land, `GALENA_EMBED` stays false and the Akta tab links out — and says why, because a
blank rectangle is worse than an honest link. Extract the duplicated shell into a small internal
package (`kancelaria-core`) only **after** both apps have used it in anger; premature extraction
here costs more than the duplication.
### 3.5 Server-to-server calls (Stage A)
Sygna→Galena calls **pass through the acting user's token** rather than using a service account, so
Galena's `authz` remains the single authority on document access and there is no privilege-escalation
seam to defend. Every outbound call goes through `integrations/galena.py`, is retried with backoff, and
records an `integration_event` row for idempotency and audit.
---
## 4. Domain model
Strict Galena layering applies: **routers → services → models**. Routers never build SQL; services own
domain logic. A bare `db.get(Model, id)` by primary key in a router is the only exception.
### 4.1 Tables
**Parties and clients**
- `party` — a person or organisation. `kind` (person/organisation), names, `pesel`, `nip`, `krs`,
`regon`, addresses, `is_pep`, `risk_rating`, `edoreczenia_address`. One table for clients, opposing
parties, courts and experts — because the same entity plays different roles in different matters,
and the conflict engine must see all of them in one place.
- `party_link` — related entities (parent company, beneficial owner, group member) with a typed
relation. Feeds conflict checking beyond exact-name matching.
- `party_alias` — normalised name forms (declension stems, former names, transliterations).
**Matters**
- `matter` — the aggregate root. `node_id` (its place in the tree), `document_node_id` (→ Galena
project), `reference` (internal number), `name`, `client_party_id`, `practice_area`, `status`,
`responsible_lawyer_id`, `originating_lawyer_id`, `opened_at`, `closed_at`, `fee_type`,
`value_in_dispute` (`wps`), and the court block: `court`, `department`, `case_signature`
(`sygnatura`), `instance`.
- `matter_party` — party + typed role (`powód`, `pozwany`, `interwenient`, `pełnomocnik strony
przeciwnej`, `biegły`, `świadek`, `sąd`) + `is_adverse` flag. The adverse flag is what the conflict
engine keys on.
- `matter_note`, `matter_task`.
**Conflicts and access**
- `conflict_check` — a run record: who ran it, against what, the candidate hits, the outcome
(`clear` / `waived` / `declined`), the waiver document, who decided. **Never deleted.** This is the
firm's evidence if a conflict is ever alleged.
- `ethical_wall` — `(matter_id, user_id, mode: allow|deny)`. Deny wins over any inherited grant.
**Time and money**
- `time_entry` — matter, user, date, `minutes` (stored as integer minutes; UI works in 0.1 h),
narrative, activity code (UTBMS optional), `billable`, `rate`, `write_off_minutes`, `invoice_id`.
- `expense` — disbursements: `opłata sądowa`, `opłata skarbowa` (17 zł), experts, translators, travel.
- `rate_card` + `rate_card_entry` ✅ **built** — per-firm, per-client and per-matter hourly rates,
effective-dated. Resolution (`services/rates.resolve`) walks matter override → matter card →
client card → firm card → house setting, and within a card person → grade → fallback, returning
the rate **and where it came from**. It resolves for the date of the work, not today.
`lawyer_profile` carries the grade, because `app_user` is byte-identical with Galena's.
- `invoice` + `invoice_line` — with the KSeF block: `ksef_number`, `ksef_status`, `ksef_sent_at`, `upo`.
- `client_deposit` + `deposit_movement` — client money held on account, per-matter balance, **check
constraint: balance never negative**.
**Deadlines and the court calendar**
- `deadline` ✅ **built** — matter, `kind`, `due_date`, `source` (`statute` / `court` /
`contract` / `internal`), `source_correspondence_id`, `owner_id`, `confirmed_by_id`,
`confirmed_at`, `completed_at`. The confirm-by-a-second-person flow is a column, not a
convention. **Escalating reminders are built** (`services/reminders.py`): sparse milestones
(14/7/3/1/0), one overdue notice, one escalation after three days to whoever manages the
matter — falling back to the owner in a solo practice — and an idempotency key enforced by a
database constraint, so the scheduler is safe to run at any frequency.
- `notification` + `notification_pref` ✅ **built** — Galena's column shape (SHARED.md) plus a
`dedupe_key` unique per recipient. Ethical walls filter recipients, so a notification can
never reveal a matter the reader is walled off from.
- `court_event` ✅ **built** — hearings: date/time, court, room, attending lawyer.
**Correspondence and integrations**
- `correspondence` ✅ **built** — one row per inbound/outbound item from e-Doręczenia, Portal
Informacyjny or post. `channel`, `direction`, `legal_service_date` (**the field that starts every
clock**), `received_at`, `external_ref`, `matter_id`, `document_path` (its location inside the
Galena project). Built ahead of the connectors on purpose: the expensive part is not fetching a
document, it is deciding what a service date means and making every derived deadline point back at
it. Items land **unassigned** — nothing guesses which matter a letter belongs to. A service date is
correctable until a deadline derives from it, then refused. Idempotency is a partial unique index on
`(channel, external_ref)`, so a connector that re-polls cannot duplicate an item.
- `integration_event` — outbound/inbound call log with an idempotency key. Every government API call
lands here.
**Intake / the CRM half**
- `lead` — enquiry, source, referrer, stage, estimated value, linked `conflict_check`, and the
conversion to a `matter`.
- `pitch` — tenders, panel appointments, RFPs.
**Compliance**
- `aml_case`, `aml_check` — CDD records, beneficial-owner verification against CRBR, PEP/sanctions
screening, risk assessment, 5-year retention. **Structurally separated from matter content**, since
the AML duty applies only to defined transactional activity and privileged advisory work must not
leak into it.
- `professional_record` — per-lawyer OC insurance policy, `ORA`/`OIRP` number, CPD points.
### 4.2 Authorization
`services/authz.py` stays the single authority, copied from Galena, with one addition:
```
effective_role(user, node) → Galena's ancestor-or-self resolver, unchanged
matter_role(user, matter) → effective_role(user, matter.node)
then: ethical_wall deny → None (404, hide existence)
ethical_wall allow → at least viewer
```
Deny-by-default for named individuals is what an information barrier actually requires; role-based
access alone cannot express it. Routers call `assert_can_read` / `assert_role` before every read and
write, exactly as in Galena.
**Walls are administered from outside the barrier.** `matters.assert_wall_admin` authorizes wall
management against the matter's **parent container**, not the matter itself. Authorizing it on the
matter would let anyone lock themselves out permanently — the deny that hides the matter also
removes their manager role on it, so there is no way back short of a DBA. Putting up a barrier is a
supervisory act, and it reads correctly as one. *(Found during implementation, by the integration
test that walls an admin and then tries to lift the wall.)*
### 4.3 Confidentiality architecture
`Tajemnica adwokacka` is a stronger regime than RODO and both apply at once. The constraints are
architectural, not policy documents:
- **EU/PL hosting, contractually named data-centre location.** Self-hosted Docker Compose is the
default deployment, which makes this the operator's choice — a genuine advantage over SaaS rivals.
- **Append-only `audit_log`** with the `app` role holding no UPDATE/DELETE — inherited from Galena and
enforced in the migration. The audit log is a confidentiality control here, not a nice-to-have.
- **Encryption** reuses Galena's self-describing blob format for anything Sygna stores at rest.
- **No client data leaves the box by default.** Any AI feature must be EU-hosted inference with
contractual no-training terms, switchable off per matter, and off by default.
- **Government API calls are the only outbound traffic**, all funnelled through `integrations/` and
logged in `integration_event`.
---
## 5. Integrations
All external I/O lives in `backend/app/integrations/`, behind a `Connector` protocol, called only from
`services/`. Never from a router. Each connector: typed config from `Settings`, `httpx` client with
timeouts and backoff, idempotency key, `integration_event` row, and a fake for tests.
| Connector | Priority | Notes |
|---|---|---|
| `edoreczenia.py` | **P0** | UA API **v3** only — v1/v2 were switched off 1 Jan 2026. Poll the mailbox, ingest EPO/EPD receipts, capture `legal_service_date`, resolve addresses via BAE, file the document into the matter's Galena project. **Request test-environment access from gov.pl on day one** — the queue, not the code, is the schedule risk. |
| `ksef.py` | **P0** | KSeF 2.0. Receiving is mandatory for everyone since 1 Feb 2026; issuing since 1 Apr 2026. Issue invoices, handle `offline24` fallback (submit by the next business day), store the KSeF number and UPO, manage certificates/tokens. |
| `registers.py` | **P1** ✅ **built (KRS + Biała lista)** | Auto-fills a party from KRS — name, legal form, NIP, REGON, address, e-mail, **and the e-Doręczenia (BAE) address**, a genuine head start on Phase 2 — plus `sposobReprezentacji`. Biała lista adds VAT status and the registered bank accounts (verify before a disbursement leaves the client account). **Correction to the original plan: the KRS API masks the names of natural persons** (`N**********`), verified against three unrelated companies. Officers and shareholders therefore *cannot* be pulled into the conflict engine from this API — Sygna records their count and functions, flags the redaction, and asks for the names by hand. CEIDG, REGON/BIR1, VIES and CRBR remain to do; CEIDG and BIR1 need credentials. |
| `pisp.py` | **P2** | Portal Informacyjny Sądów Powszechnych. Sync case events, hearings and served documents; capture the deemed-service date. No open public API — access mechanics must be established first (incumbents ship connectors, so it is possible). **Filing via PI becomes obligatory for adwokaci/radcowie on 1 Mar 2027** — that date anchors the roadmap. |
| `saos.py` | **P3** | Open case-law API. Free case-law lookup without a LEX/Legalis licence. |
| `galena.py` | **P0** | Project creation, file write, tree read — see §3.5. |
Protocol details (SOAP vs REST, signature format, auth) for e-Doręczenia and KSeF must be **verified
against the current gov.pl specification** before implementation; treat anything in this document
about their wire format as directional.
---
## 6. Frontend
Same shell, new screens. Hash routes mirror Galena's `#/n/<id>` style.
| Route | Screen |
|---|---|
| `#/` | Pulpit — my deadlines this week, unconfirmed service dates, unbilled time, open drafts |
| `#/matters` · `#/m/<id>` | Matter list · matter detail (parties, deadlines, time, documents, correspondence) |
| `#/clients` · `#/p/<id>` | Party list · party detail with related entities and matter history |
| `#/time` | Time sheet — a hand-rolled editable grid, following the `_csvMount`/`_csvRender` pattern |
| `#/calendar` | Deadlines + hearings. The one screen that may justify a committed Vite bundle |
| `#/billing` | Pro-forma review → invoice → KSeF status |
| `#/inbox` | e-Doręczenia and Portal Informacyjny items awaiting assignment to a matter |
| `#/intake` | Leads and pitches, with the conflict gate |
| `#/admin` | Users, access, integrations, AML settings, backup |
**Conventions carried over:** `esc()` every dynamic value; bearer token in memory only, cookie session
primary; one render funnel per screen so listeners do not accumulate; unsaved-changes guard on any
form; `font-variant-numeric: tabular-nums` everywhere money and time line up in columns.
**PL-first i18n.** Source strings stay English (that is how `I18N.pl` keys work), but the Polish
translation is part of the definition of done for every screen, and the legal vernacular in §7 is
authoritative for the PL side.
---
## 7. Terminology — Polish UI, English internals
Galena's first invariant is "de-jargoned UI, technical internals". Sygna's version: **the UI speaks
the vernacular of a Polish law firm; code, routes and tables stay English.**
| UI (PL) | Code / route |
|---|---|
| Sprawa | `matter` |
| Sygnatura akt | `case_signature` |
| Klient / Strona | `party` (`client_party_id`, `matter_party`) |
| Strona przeciwna | `matter_party.is_adverse` |
| Konflikt interesów | `conflict_check` |
| Termin | `deadline` |
| Data doręczenia | `legal_service_date` |
| Rozprawa | `court_event` |
| Karta czasu pracy | `time_entry` |
| Wydatek / Opłata | `expense` |
| Faktura | `invoice` |
| Depozyt klienta | `client_deposit` |
| Akta sprawy | the linked Galena project |
| Kancelaria / Dział / Zespół | `node` (workspace / group / folder) |
---
## 8. Repository layout
```
sygna/
backend/
app/
main.py config.py db.py deps.py errors.py security.py enums.py schemas.py seed.py
observability.py logging_config.py
models/ identity (copied) · node (copied) · party · matter · conflict
· time · billing · deadline · correspondence · compliance
services/ auth · authz (copied + ethical walls) · nodes (copied)
· parties · matters · conflicts · deadlines · time · billing
· correspondence · aml · audit · notify · stats · search · settings
integrations/ base (Connector protocol) · galena · edoreczenia · ksef
· registers · pisp · saos
routers/ auth · users · admin · nodes · permissions · parties · matters
· conflicts · deadlines · time · billing · correspondence
· intake · dashboard · search · health
alembic/ 0001_initial (pgcrypto, enums, create_all, least-privilege grants)
scripts/license_gate.py
tests/ DB-free unit tests + integration gated on SYGNA_RUN_INTEGRATION=1
frontend/ index.html · app.css · app.js · sw.js (no build)
db/init/01-roles.sh
docs/CRMecenas-Discovery-Report.md
docker-compose.yml · Caddyfile · .env.example · .github/workflows/ci.yml
PLAN.md · SHARED.md (Galena sync list) · CLAUDE.md · README.md · LICENSE (Apache-2.0)
```
---
## 9. Invariants (destined for `CLAUDE.md`)
1. **Polish vernacular UI, English internals.** Keep the §7 mapping consistent across console and docs.
2. **Strict layering:** routers → services → models. No `select(...)`/`db.add`/`db.execute` in a router.
3. **`services/authz.py` is the only access authority.** Ethical-wall deny wins over any inherited
grant. No access → 404, never 403 (existence is itself privileged).
4. **A matter is a leaf of the node tree**, mirroring Galena's project rule. Its documents live in the
linked Galena project, never in Sygna's database.
5. **Append-only audit.** The `app` DB role holds no UPDATE/DELETE on `audit_log`. `migrator` owns DDL.
6. **`conflict_check` rows are never deleted or edited.** Supersede, don't mutate.
7. **`legal_service_date` is set once, from the source system, and is never inferred.** Every derived
deadline points back to the `correspondence` row it came from.
8. **All external I/O goes through `integrations/`**, with an `integration_event` row. No `httpx` call
anywhere else in the codebase.
9. **Files shared with Galena stay diff-clean.** Change both repos in one commit; record it in
`SHARED.md`.
10. **Core stays permissive.** Apache-2.0; CI denies GPL/AGPL/SSPL. Copyleft or heavyweight components
are optional sidecars, never core — same policy as Galena.
11. **No build step for the console.** The single exception is a committed Vite bundle with a working
fallback, following the `frontend/static/editor.js` precedent.
12. **Money in integer minor units, time in integer minutes.** No floats anywhere near an invoice.
---
## 10. Roadmap
**Phase 1 — the spine.** ✅ **Done (Aug 2026).** Repo scaffold mirroring Galena (compose, Caddy,
roles, CI, licence gate). Copied identity/node/authz/errors layer. `party` (+aliases, links),
`matter`, `matter_party`, `ethical_wall`, `conflict_check`, `lead`, `deadline`, `court_event`,
`time_entry` — 18 tables, 70 routes. Console in Polish: pulpit, matters, matter detail
(parties / deadlines / time / access), parties, intake, timesheet, admin. Conflict check at
intake — blocking, with a permanent decision record. Galena case file created per matter and
deep-linked. Verified against a real PostgreSQL 16: migration + seed, 47 tests (32 DB-free +
15 integration), least-privilege grants, licence gate, console boots clean.
*Not verified:* the Galena connector against a live Galena instance — none was available.
**Phase 2 — the Polish moat.** The receiving end is **already built**: the `#/inbox` screen,
assignment to a matter, and deadlines derived from a service date all work today with manual entry.
What is left is the feed — e-Doręczenia (UA API v3 + BAE) writing through
`services/correspondence.record`, so the connector inherits the rules rather than re-implementing
them. Then KSeF 2.0 issuing and receiving. Then the registers connector for party auto-fill.
*Start the e-Doręczenia test-environment request before writing any of this.*
**Phase 3 — money.** ✅ **complete.** Disbursements with pass-through VAT handling, invoices with
a draft → approve → issue flow, credit notes, client-money deposits on a ledger that cannot go
negative, and the full management set: **realisation** (billing and collection, the latter net of
VAT), **utilisation** against real Polish working days, **matter profitability** against a cost
rate — reporting `incomplete` rather than a flattering zero when one is missing — **lock-up**
(WIP days + debtor days) and an **aged-debt** ageing table. Every report is filtered through the
authz resolver. KSeF columns exist; the connector is Phase 2.
**Phase 4 — the wedge.** Portal Informacyjny sync. Hardest integration, highest switching cost, and
tied to the 1 Mar 2027 obligation.
**Phase 5 — depth.** Document generation with Polish declension, PAdES signing via a QTSP, the AML/KYC
module, a client portal, and the Stage B/C convergence with Galena. *(The court-fee and `koszty
zastępstwa` calculators were pulled forward and are built — `services/fees.py`, pure computation with
the schedules as auditable data. The figures still need checking against the current statutes.)*
---
## 11. Open questions and risks
**Blocking, needs an external answer**
- e-Doręczenia test-environment access — lead time unknown, gates Phase 2.
- Portal Informacyjny integration for third-party vendors — the access mechanism and its legal basis
must be established before Phase 4 can be scheduled.
**Decided (2026-08-13)**
- **Deployment: self-hosted, as Galena.** Docker Compose + Caddy, no managed dependency. A hosted
offering may follow but never replaces the self-hosted path — it is what makes `tajemnica
adwokacka` defensible.
- **Shared code: vendor + enforce, then merge.** `scripts/shared_check.py` fails the build when a
file declared byte-identical in SHARED.md drifts; a monorepo (`apps/*`, `packages/core`) comes at
Stage B. No separately-versioned package: a shared library versioned apart from the schema it
describes buys a distributed-versioning problem for two apps that deploy together.
- **In-house departments: configurable.** `practice_mode` setting, not a second product.
- **Mobile breakpoint: 880px**, matching Galena.
- **Commercial company-data provider: yes.** Wanted for unmasked officers and beneficial owners.
Build it behind the `integrations/` boundary, **off by default**, with the confidentiality
controls below — a conflict search discloses that the firm is considering acting for or against
a named party, so every query is a disclosure and needs a DPA, a sub-processor entry, local
caching so a name is sent once, and an audit row per outbound lookup.
**Technical risks**
- **The no-build console versus the calendar screen.** The month view is the one place the constraint
bites. Mitigation is the committed-bundle precedent; decide before Phase 1 ends.
- **Polish full-text search.** PostgreSQL ships no Polish configuration. Preferred route is
**Morfologik** (BSD) for stemming; the Hunspell Polish dictionary is tri-licensed GPL/LGPL/MPL, so
take the **MPL-2.0** branch to stay inside the licence gate. Validate this before relying on it.
- **Name clearance.** "Sygna" has had no trademark or domain check.
- **Government API instability.** KSeF and e-Doręczenia specs have both moved repeatedly. The
`integrations/` boundary plus `integration_event` replay is the insurance; version every connector.
+219
View File
@@ -0,0 +1,219 @@
# Sygna
**System zarządzania kancelarią** — practice management for Polish law firms: clients, matters,
parties, conflict checking, deadlines and time recording. Self-hosted, Apache-2.0, no copyleft
dependencies.
Sygna is the sibling of **[Galena](https://github.com/Alpaq92/galena)**, a git-backed cloud
drive. Sygna owns *matters, people, time and money*; Galena owns *documents and their history*.
A matter's case file (`akta sprawy`) is a Galena project, referenced by
`matter.document_node_id` — neither application duplicates the other.
Status: **Stage A / Phase 1**. See [`PLAN.md`](PLAN.md) for the roadmap and the compatibility
contract with Galena, and [`docs/CRMecenas-Discovery-Report.md`](docs/CRMecenas-Discovery-Report.md)
for the research behind it.
---
## Why not a generic CRM
A generic CRM models *lead → deal → close*. A law firm models *client → matter → work → bill*,
and the matter outlives the deal by a decade. Three things make this a vertical product rather
than a Salesforce configuration:
**Conflict of interest checking is a blocking gate.** Before a matter can be opened, Sygna
searches every client, former client, opposing party and related entity — with matching that
copes with Polish declension (`Kowalski` / `Kowalskiego` / `Kowalskiemu`), folded diacritics
(`Łódź` = `Lodz`) and legal-form noise (`sp. z o.o.` = `S.A.` = nothing) — and refuses to open
the matter until a human records a decision with a reason. That record can never be edited or
deleted afterwards; the database enforces the second half. One check opens one matter, so a
`clear` result from last month cannot be reused when the facts have changed.
**Deadlines are existential.** A missed `termin zawity` is malpractice, so a statutory or court
deadline is not "managed" until a **second person** has confirmed it — and `confirm` refuses the
person who entered it. Derived deadlines record how the date was reached in words
(`doręczenie 2026-08-03 + 14 dni`) and point back at the correspondence that started the clock.
That link is enforced, not decorative: a service date can be corrected until a deadline depends
on it and is refused afterwards, and correspondence with derived deadlines cannot be deleted. A
deadline that has lost the document proving where its date came from is worse than a blocked
delete.
**Ethical walls are deny-by-default for named individuals.** Role-based access cannot express
"everyone in the department except Anna", which is what an information barrier is. A `deny`
removes every role on that matter — owner, manager and instance administrator included — and the
matter returns **404, not 403**, because its existence is itself privileged. Walls are
administered from *outside* the barrier, so walling yourself off is never a one-way door.
---
## Quick start
### Docker (the whole stack)
```bash
cp .env.example .env # then edit the passwords
docker compose up -d --build
```
Postgres → migrate (+seed) → backend → Caddy on `:80`. Only Caddy is published; the backend and
database are expose-only. Sign in with `BOOTSTRAP_ADMIN_EMAIL` / `BOOTSTRAP_ADMIN_PASSWORD`.
### Local development
You need PostgreSQL 16 and Python 3.12.
```bash
cd backend && python -m venv .venv && .venv/bin/pip install -r requirements-dev.txt
```
Create the least-privilege roles (this is what `db/init/01-roles.sh` does in Docker):
```bash
psql -U postgres -d sygna -v ON_ERROR_STOP=1 -c "CREATE ROLE migrator LOGIN PASSWORD 'migpw'; CREATE ROLE app LOGIN PASSWORD 'apppw'; GRANT CONNECT ON DATABASE sygna TO migrator, app; ALTER SCHEMA public OWNER TO migrator; GRANT USAGE ON SCHEMA public TO app; CREATE EXTENSION IF NOT EXISTS pgcrypto;"
```
Then, with `DATABASE_URL` and `MIGRATION_DATABASE_URL` pointing at it:
```bash
cd backend && alembic upgrade head && python -m app.seed
```
```bash
cd backend && .venv/bin/python -m uvicorn app.main:app --port 8032 --app-dir .
```
The console is served by the backend at `http://localhost:8032` (Caddy serves it directly in
production). On Windows write `.env` **without a BOM** — see the gotchas in
[`CLAUDE.md`](CLAUDE.md).
`SEED_DEMO=true` creates a small firm whose demo data is chosen to exercise the conflict engine:
*Nowak Transport sp. z o.o.* is a client in one matter and the opposing party in another, so the
first conflict search a new user runs returns a real hit rather than an empty screen.
### Tests
```bash
cd backend && pytest # DB-free; integration auto-skips
SYGNA_RUN_INTEGRATION=1 pytest # full API loop against a migrated + seeded Postgres
python scripts/license_gate.py # deny GPL/AGPL/SSPL
```
---
## Architecture
| | |
|---|---|
| **Stack** | FastAPI · SQLAlchemy 2 · Alembic · PostgreSQL 16 (`pg8000`, pure-Python) · Argon2id · server-side cookie sessions · vanilla-JS console with **no build step** |
| **Layering** | routers → services → models, enforced by convention. Routers never build SQL; `services/authz.py` is the only access authority. |
| **Tree** | `workspace` (kancelaria) → `group`/`folder` (dział, zespół) → `matter`. A **matter is a leaf**, mirroring Galena's project rule. Roles `viewer < editor < approver < manager` inherit down the tree; the highest ancestor-or-self grant wins. |
| **Least privilege** | `migrator` owns DDL; the runtime `app` role is DML-only, cannot mutate `audit_log`, and cannot delete `conflict_check`. |
| **Money & time** | Integer grosze and integer minutes. Time rounds **up** to 6-minute units; the amount rounds **down**, in the client's favour. Court fees round up to a whole złoty — art. 21 u.k.s.c., not a preference. |
| **Rates** | Effective-dated cards scoped to a matter, a client or the firm. Resolution reports its own source; recorded time keeps a rate snapshot, so editing a card never re-prices the past. |
| **Integrations** | All external I/O is behind `app/integrations/`, with bounded retries and a single `UpstreamError`. A connector failure never breaks the primary action. |
| **License** | Apache-2.0. CI gate fails the build on any GPL/AGPL/SSPL dependency. |
### Galena integration
Set `GALENA_BASE_URL` and each new matter gets a Galena project as its case file. Calls carry
**the acting user's token**, never a service account, so Galena's authorization stays the single
authority on document access and there is no privilege-escalation seam between the two
applications. Leave it empty and the integration is a clean no-op: matters are created without a
case file and the console says so.
Stage A keeps the two databases separate, so the two applications have separate user
directories. Stage B introduces a shared `core` schema — and because Galena's sessions are
already DB-backed with hashed tokens, a shared `core.session` plus a parent-domain cookie gives
real SSO with no new protocol. See [`PLAN.md`](PLAN.md) §3.4 and [`SHARED.md`](SHARED.md).
---
## Roadmap
**Phase 1 — the spine.** *(done)* Clients, matters, typed parties, conflict checking, deadlines,
time recording, per-matter access with ethical walls, immutable audit log, Polish console.
**Phase 1½ — the correspondence spine.** *(done)* An inbox where every incoming document lands
unassigned, a service date established by hand, and deadlines derived from it with full
provenance. Built before the connectors on purpose: the hard part was never fetching a document,
it was deciding what a service date means. Items from e-Doręczenia and the Portal Informacyjny
that have **no** service date yet get their own count on the pulpit — each one is a clock that
may already be running while nobody is watching it.
**Phase 1¾ — money groundwork.** *(done)* A **court-fee calculator** (opłata sądowa, koszty
zastępstwa procesowego, opłata skarbowa) whose schedules are held as auditable data with the
statute on every bracket — and which states its own version and tells you to verify, because a
calculator that looks authoritative and is out of date is worse than one that admits it. Plus
**rate cards**: effective-dated and scoped, resolved matter override → matter card → client card
→ firm card → house setting, and within a card person → grade → fallback. The resolver reports
*where the rate came from*, because the first question about any invoice line is "why 520 and
not 450". Rates resolve for the date of the work, and recorded time keeps its snapshot.
**Phase 1½+ — reminders.** *(done)* A deadline system that needs you to remember to look at it
is not a deadline system, so the engine now tells people: milestones at 14/7/3/1/0 days, an
overdue notice once, and an escalation after three days to whoever manages the matter — falling
back to the owner in a solo practice. It also chases the two things that quietly rot: incoming
post with no service date, and conflict checks nobody has decided.
Every reminder carries a dedupe key enforced by a **database constraint**, so the scheduler can
run as often as it likes and `POST /admin/reminders/run` is safe to press at any time. Ethical
walls apply to notifications too — a wall a notification leaks through is not a wall.
**Phase 1⅞ — public registers.** *(done)* Look a company up by KRS and its record fills itself
in — name, legal form, NIP, REGON, address, and the **e-Doręczenia (BAE) address**, which is
Phase 2 groundwork arriving early. Biała lista gives VAT status and the registered bank
accounts, so a counterparty's account can be checked before money leaves the client account.
A register fills blanks and never overwrites what the firm deliberately recorded.
*The honest limit:* the KRS API **masks the names of natural persons** — a board member comes
back as `N**********`. Sygna reports how many officers there are and what they do, says plainly
that the names are redacted, and asks you to enter them by hand. Inventing a party from a masked
name would put a fiction into the register that decides whether the firm may take a case.
**Phase 3 — money.** *(done)* Disbursements that know a recharged court fee carries no VAT of
yours; invoices that go draft → approved → issued, where **approval records who read the
narratives the client is about to read**; a number assigned only at issue, because a gap in the
sequence is a question from the tax office; and an issued invoice that can only be corrected by
a credit note, which mirrors it and hands the work back to unbilled so it can be re-billed
rather than quietly written off. Client money sits on its own ledger with a balance that
**cannot go negative** — a database constraint, not a good intention.
And the numbers partners ask for: **realisation** (how much of the work's nominal value survived
to an invoice, and how much of that turned into cash — net of VAT, because VAT is not revenue),
**utilisation** measured against real Polish working days with the public holidays computed
properly, **matter profitability**, **lock-up** (how many days a złoty of work waits to become
cash) and an **aged-debt** table. Every one of them filtered through the same permission
resolver as everything else — a management report that quietly includes a walled matter is a
leak wearing a spreadsheet. A matter whose time has no cost rate behind it reports
*incomplete* rather than a flattering margin computed from zeroes.
**Phase 2 — the Polish moat.** The feed. e-Doręczenia (UA API v3 + BAE — v1/v2 were switched off
on 1 Jan 2026) writes through the same `services/correspondence.record` the console uses, so the
connector inherits the service-date and idempotency rules instead of re-implementing them. Then
KSeF 2.0, then KRS / CEIDG / Biała lista for party auto-fill. *Request the e-Doręczenia test
environment before writing any of it — the queue, not the code, is the schedule risk.*
**Phase 3 — money.** Rate cards, pro-forma review, invoices with KSeF, disbursements, client
deposits, and the reports partners ask for: WIP, realisation, utilisation, lock-up.
**Phase 4 — the wedge.** Portal Informacyjny sync. Hardest integration, highest switching cost,
and tied to filing via PI becoming obligatory for `adwokaci`/`radcowie` on **1 March 2027**.
**Phase 5 — depth.** Document generation with Polish declension, PAdES signing via a QTSP, the
AML/KYC module, a client portal, court-fee and `koszty zastępstwa` calculators, and Stage B/C
convergence with Galena.
---
## Confidentiality
`Tajemnica adwokacka` is a stronger regime than RODO and both apply at once, so the constraints
are architectural rather than policy documents: self-hosted by default (the operator chooses
where the data lives), an append-only audit log recording who opened which client's file, and
government APIs as the only outbound traffic — all of it behind one boundary that logs what it
sends. Any future AI feature must be EU-hosted inference with contractual no-training terms,
switchable off per matter, and off by default.
## License
Apache-2.0. See [`LICENSE`](LICENSE).
+104
View File
@@ -0,0 +1,104 @@
# Shared with Galena
Sygna and Galena are separate deployments today (Stage A) that are meant to become one system
(Stage B: a shared `core` schema and a shared session table → SSO with no new protocol; see
[`PLAN.md`](PLAN.md) §3).
That only stays cheap if the shared files stay **diff-clean**. This file is the list.
> **The rule:** if a file below must change, change it in **both repositories in the same
> commit** and update the note here. Do not fork behaviour silently. A divergence that nobody
> wrote down turns Stage B from a data move into a rewrite.
Galena is assumed to live at `../Galena` relative to this repository.
**The rule is enforced, not merely written down:**
```bash
cd backend && python scripts/shared_check.py # GALENA_REPO=... to point elsewhere
```
It parses the table below and fails if a row marked exactly `same` is not byte-identical. Rows
marked `same + …` are documented additive divergences and are reported, not failed. When Galena
is not checked out the check skips rather than fails. It runs in CI after the licence gate.
*It earned its keep on the first run:* eight files had drifted — every one of them because a
comment saying "copied from Galena" had been added to it. The provenance notes were what broke
the provenance guarantee. Provenance belongs here, in this file, not in the shared sources.
## Byte-identical (copied, no edits)
| Sygna | Galena | Why it matters |
|---|---|---|
| `backend/app/models/base.py` | same | `NAMING_CONVENTION`, `UUIDPkMixin` (`gen_random_uuid()`), `TimestampMixin`. The UUID PKs are what make ids globally unique across both databases — the precondition for merging. |
| `backend/app/models/types.py` | same | `SafeInet`, `pg_enum` |
| `backend/app/models/identity.py` | same | `AppUser`, `Session`, `AppSetting`, `AuditLog` — the tables that become `core.*` at Stage B |
| `backend/app/errors.py` | same + `UpstreamError` | RFC 9457 Problem Details. Both apps' clients parse one error format. **Sygna adds `UpstreamError` (502)**; harmless to port back to Galena. |
| `backend/app/services/audit.py` | same | |
| `backend/app/services/auth.py` | **diverged — see below** | Sygna adds `get_user` / `set_password`; Galena has since added the whole app-token feature. |
| `backend/app/db.py` | same | engine with `hide_parameters=True` |
| `backend/alembic/env.py` | same | |
| `backend/scripts/license_gate.py` | same | deny GPL/AGPL/SSPL |
| `db/init/01-roles.sh` | same | `app` (DML) + `migrator` (DDL) |
## Same shape, intentionally adapted
| File | Divergence | Reason |
|---|---|---|
| `backend/app/models/node.py` | Drops `review_policy` / `encryption_mode` | Those are Galena project columns. Sygna never creates a project row; it references one by id. |
| `backend/app/enums.py` | `NodeKind` gains `matter`; keeps `project` | `matter` is Sygna's leaf, mirroring Galena's `project`. `project` is kept as a label Sygna never writes, so a Stage B merge into one enum type needs no surgery. `NodeRole`, `PrincipalType` unchanged. |
| `backend/app/services/authz.py` | Adds ethical walls, `readable_node_ids`, `access_state` gains `walled` | A `deny` beats every inherited grant including admin, and walls are administered from the parent container. Galena has no equivalent concept; porting it back would be additive. |
| `backend/app/services/nodes.py` | `LEAF_KINDS` replaces the hardcoded project check; refuses to create `project`; slug folds Polish diacritics; no git calls | Sygna has no git. The leaf rule is otherwise Galena's, unchanged. |
| `backend/app/config.py` | Adds `galena_*`, `seed_demo`; drops encryption / plugins / backup / VAPID / SMTP | Extended, never restructured. |
| `backend/app/deps.py` | Cookie name `sygna_session` | At Stage B both read one `core.session` table and the cookie is scoped to the parent domain. |
| `backend/app/main.py` | CSP has **no** third-party origins; no ReaderJS frame branch; no backup lifespan | Sygna's console loads nothing from a CDN. |
| `backend/alembic/versions/0001_initial.py` | Sygna's `ENUMS`; adds `REVOKE DELETE ON conflict_check` | Same structure: create enums → `create_all` → grants. |
## Outstanding: Galena's app tokens (found by the drift check, 2026-08-13)
Galena grew a **named app-token** credential — a desktop/CLI token sharing the `session` table,
with a *sliding idle expiry* and a read / read_write scope enforced in `deps.get_current_user`.
The drift check caught it the same day.
What has been done: `models/identity.py` is byte-identical again, so **Sygna's `session` table
carries Galena's new columns** (`kind`, `name`, `scope`, `idle_days`, `token_prefix`, and
`ix_session_user_kind`). They are additive with server defaults, so Sygna's login sessions are
valid rows without writing them.
What has **not** been done, deliberately — it is a feature port, not a merge fix:
| Galena has | Sygna does not |
|---|---|
| `enums.SessionKind`, `enums.TokenScope` | — |
| `services/auth.create_app_token`, sliding idle renewal | — |
| `security.generate_app_token`, `token_display_prefix` | — |
| scope enforcement in `deps.get_current_user` | — |
**Stage B action:** port these before `core.session` is shared, or two applications will write
one credential table through two different code paths — and Sygna would ignore a `read`-scoped
token's restriction entirely. Until then Sygna simply never mints an app token, and rows it
creates fall back to `kind='session'`, `scope='read_write'`, which is correct for what it does.
## Deliberate divergences
**i18n direction is inverted.** Galena's source strings are English with `I18N.pl` translating
to Polish. Sygna's source strings are **Polish** with `I18N.en` translating to English. The
mechanism is identical — `_tr` / `_trAttr` / `localize`, matching on source text, with
`data-no-i18n` opt-outs — only the source language differs. Sygna is a Polish-first product for
a Polish profession; writing its UI in translation would read like one. At Stage C, when the two
consoles share a shell, the shell's strings follow whichever app owns the file.
**Brand colour.** Galena: Open Color `violet8` (#5f3dc4), used **only** on the app icon. Sygna:
Open Color `cyan8` (#0c8599), used on the app icon **and** on icon tiles, the avatar and the
focus ring — a deliberate divergence. UI chrome (buttons, nav, toolbar glyphs) stays monochrome
in both. The two brands must stay distinguishable at launcher size once a shared shell exists.
**Dev ports.** Galena 8012 / 8014 / 8021 / 8023; Sygna 8032 / 8034 / 8041. Both stacks can run
side by side.
## Not yet shared, but will be
At Stage C the console shell (`api()`, `esc()`, `toast()`, `ICN`, theme handling, the i18n
layer, the `app.css` token set) is a candidate for extraction into an internal package. **Do not
extract it before both applications have used it in anger** — a premature abstraction here costs
more than the duplication it removes.
+7
View File
@@ -0,0 +1,7 @@
# Keep the build context small + Linux-clean (the venv holds Windows binaries).
.venv/
__pycache__/
*.py[cod]
.pytest_cache/
*.egg-info/
.coverage
+20
View File
@@ -0,0 +1,20 @@
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd -m app && mkdir -p /data && chown -R app /data /app
ENV DATA_DIR=/data
USER app
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=5s --retries=10 \
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/api/v1/health').status==200 else 1)"
# Trust X-Forwarded-For only from the reverse proxy. The default '*' is safe ONLY because the
# backend is expose-only in docker-compose (never host-published) — Caddy is the sole ingress.
# If you publish this port directly, set FORWARDED_ALLOW_IPS to the proxy's address so client IPs
# in the audit log can't be spoofed.
ENV FORWARDED_ALLOW_IPS=*
CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port 8000 --forwarded-allow-ips \"$FORWARDED_ALLOW_IPS\""]
+38
View File
@@ -0,0 +1,38 @@
[alembic]
script_location = alembic
prepend_sys_path = .
# The URL is overridden in env.py from MIGRATION_DATABASE_URL (the migrator role).
sqlalchemy.url = postgresql+pg8000://migrator:migrator@localhost:5432/sygna
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
+46
View File
@@ -0,0 +1,46 @@
"""Alembic environment — uses MIGRATION_DATABASE_URL (the DDL `migrator` role)."""
from __future__ import annotations
import sys
from logging.config import fileConfig
from pathlib import Path
from alembic import context
from sqlalchemy import engine_from_config, pool
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # put backend/ on sys.path
from app.config import get_settings # noqa: E402
from app.models import Base # noqa: E402
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
config.set_main_option("sqlalchemy.url", get_settings().migration_database_url)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
context.configure(url=config.get_main_option("sqlalchemy.url"),
target_metadata=target_metadata, literal_binds=True,
dialect_opts={"paramstyle": "named"})
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.", poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+92
View File
@@ -0,0 +1,92 @@
"""Initial schema: pgcrypto, native enums, all tables, and least-privilege grants.
Same shape as Galena's 0001 (see SHARED.md): tables come from the ORM metadata — after the enum
types exist — so the migration stays in lockstep with the models. Enums, the pgcrypto extension
and the append-only audit grant are explicit DDL the runtime `app` role can never perform.
Adding a model needs no change here; the table is picked up automatically. Adding an ENUM does —
put it in the ENUMS map below.
"""
from __future__ import annotations
from alembic import op
from app.models import Base
revision = "0001"
down_revision = None
branch_labels = None
depends_on = None
ENUMS = {
# shared with Galena — keep the labels identical, including the ones Sygna never writes
# (`project`), so a Stage B merge into one `core` schema needs no type surgery.
"node_kind": ["workspace", "group", "folder", "project", "matter"],
"node_role": ["viewer", "editor", "approver", "manager"],
"principal_type": ["user", "group"],
# Sygna's own
"party_kind": ["person", "organisation"],
"party_role": ["client", "opponent", "opponent_counsel", "court", "expert", "witness",
"intervener", "other"],
"party_relation": ["parent_company", "subsidiary", "beneficial_owner", "board_member",
"spouse", "related"],
"matter_status": ["prospect", "open", "suspended", "closed", "archived"],
"fee_type": ["hourly", "flat", "capped", "retainer", "success", "court_appointed",
"pro_bono"],
"deadline_kind": ["procedural", "limitation", "hearing", "contractual", "internal"],
"deadline_source": ["statute", "court", "contract", "internal"],
"conflict_outcome": ["pending", "clear", "waived", "declined"],
"correspondence_channel": ["edoreczenia", "court_portal", "post", "email", "in_person",
"other"],
"correspondence_direction": ["incoming", "outgoing"],
"correspondence_status": ["unassigned", "assigned", "filed", "ignored"],
"risk_rating": ["low", "medium", "high"],
"expense_kind": ["court_fee", "stamp_duty", "expert", "translation", "travel", "copies",
"enforcement", "other"],
"invoice_kind": ["proforma", "invoice", "credit_note"],
"invoice_status": ["draft", "approved", "issued", "paid", "cancelled"],
"ksef_status": ["not_sent", "pending", "accepted", "rejected", "offline"],
"deposit_movement_kind": ["deposit", "refund", "applied", "expense", "correction"],
"seniority": ["partner", "counsel", "senior_associate", "associate", "trainee",
"paralegal", "other"],
"lead_stage": ["new", "qualifying", "proposal", "won", "lost"],
"notification_kind": ["deadline_due", "deadline_overdue", "deadline_unconfirmed",
"correspondence_unassigned", "service_date_missing",
"conflict_pending", "matter_assigned"],
"wall_mode": ["allow", "deny"],
}
_GRANTS = """
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'app') THEN
GRANT USAGE ON SCHEMA public TO app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app;
-- Append-only audit: the runtime role may insert + read, never mutate.
REVOKE UPDATE, DELETE ON audit_log FROM app;
-- A conflict check is evidence: it can never be erased. UPDATE stays granted because
-- recording the human decision (and linking the matter it opened) writes to the row once;
-- services/conflicts.decide() refuses a second decision, so the row is immutable in
-- practice while the database guarantees the harder half — that it still exists.
REVOKE DELETE ON conflict_check FROM app;
END IF;
END $$;
"""
def upgrade() -> None:
bind = op.get_bind()
op.execute('CREATE EXTENSION IF NOT EXISTS "pgcrypto"')
for name, values in ENUMS.items():
labels = ", ".join(f"'{v}'" for v in values)
op.execute(f"CREATE TYPE {name} AS ENUM ({labels})")
Base.metadata.create_all(bind=bind)
op.execute(_GRANTS)
def downgrade() -> None:
bind = op.get_bind()
Base.metadata.drop_all(bind=bind)
for name in ENUMS:
op.execute(f"DROP TYPE IF EXISTS {name}")
op.execute('DROP EXTENSION IF EXISTS "pgcrypto"')
+3
View File
@@ -0,0 +1,3 @@
"""Sygna — practice management for Polish law firms."""
__version__ = "0.1.0"
+112
View File
@@ -0,0 +1,112 @@
"""Typed application settings, sourced from environment variables / .env.
Same shape as Galena's config.py (see SHARED.md) — extended, never restructured.
"""
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
# Core — defaults fail-closed (production hides error detail + enables Secure cookies).
# Set APP_ENV=development explicitly for local plain-HTTP work.
app_env: str = "production"
app_base_url: str = "http://localhost"
# Database (runtime = least-privilege "app" role; migrator = DDL)
database_url: str = "postgresql+pg8000://app:app@localhost:5432/sygna"
migration_database_url: str = "postgresql+pg8000://migrator:migrator@localhost:5432/sygna"
# Working directory for anything written to disk (exports, generated documents).
data_dir: str = "data"
# Auth / sessions (cookie-based, DB-backed — the shared-session seam for Stage B SSO)
session_ttl_hours: int = 12
login_max_attempts: int = 5
login_lockout_minutes: int = 15
# None → auto-detect per request scheme (Secure over HTTPS only). Set true/false to force.
# An empty env value (SESSION_COOKIE_SECURE=) is treated as None so it never crashes startup.
session_cookie_secure: bool | None = None
@field_validator("session_cookie_secure", mode="before")
@classmethod
def _blank_secure_is_auto(cls, v):
if isinstance(v, str) and v.strip() == "":
return None
return v
# CORS — empty by default (same-origin design). Comma-separated origins to allow a
# separately-served console in dev.
cors_allow_origins: str = ""
# Bootstrap admin (seed)
bootstrap_admin_email: str = "admin@example.com"
bootstrap_admin_password: str = "admin12345"
seed_demo: bool = True
# ── Galena, the document store (PLAN.md §3.5) ────────────────────────────────
# Empty base URL → the integration is a no-op: matters are created without a case
# file and the console says so. Calls carry the ACTING USER's token, never a service
# account, so Galena's authz stays the single authority on document access.
galena_base_url: str = ""
galena_console_url: str = ""
galena_casefile_parent_id: str = ""
galena_timeout_seconds: float = 15.0
# Reminders. The scheduler is an in-process asyncio task, so in a multi-instance deploy it
# should run on one instance only — set false on the others.
reminders_enabled: bool = True
reminder_interval_hours: int = 6
# OpenTelemetry (opt-in)
otel_enabled: bool = False
otel_service_name: str = "sygna-backend"
otel_exporter_otlp_endpoint: str = "http://otel-collector:4317"
@property
def is_production(self) -> bool:
return self.app_env.lower() == "production"
@property
def cors_origins_list(self) -> list[str]:
return [o.strip() for o in self.cors_allow_origins.split(",") if o.strip()]
@property
def exports_dir(self) -> Path:
return Path(self.data_dir) / "exports"
@property
def galena_enabled(self) -> bool:
return bool(self.galena_base_url.strip())
# Stage C: embed Galena's document viewer inside Sygna's matter screen instead of only
# linking to it. Requires the two apps to share a parent domain AND a matching change on
# Galena's side (its CSP `frame-ancestors` and session-cookie domain) — see PLAN.md §3.4.
# Off by default, because switched on against an unprepared Galena it yields a blank frame.
galena_embed: bool = False
@property
def galena_console(self) -> str:
"""Where the console deep-links for a case file. Falls back to the API base URL,
which is correct for the usual single-origin Galena deployment."""
return (self.galena_console_url or self.galena_base_url).rstrip("/")
@property
def galena_origin(self) -> str:
"""Scheme + host + port of Galena's console — what a CSP `frame-src` needs."""
console = self.galena_console
if not console:
return ""
parts = console.split("/")
return "//".join([parts[0], parts[2]]) if len(parts) > 2 else console
@lru_cache
def get_settings() -> Settings:
return Settings()
+39
View File
@@ -0,0 +1,39 @@
"""SQLAlchemy engine + session factory (runtime `app` role, DML only)."""
from __future__ import annotations
from collections.abc import Iterator
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from .config import get_settings
settings = get_settings()
engine = create_engine(
settings.database_url,
pool_pre_ping=True,
pool_size=5,
max_overflow=10,
future=True,
# Keep bound parameter values out of exception messages and logs so an unexpected DB
# error can't leak row data.
hide_parameters=True,
)
SessionLocal = sessionmaker(
bind=engine,
autoflush=False,
autocommit=False,
expire_on_commit=False,
class_=Session,
)
def get_db() -> Iterator[Session]:
"""FastAPI dependency yielding a request-scoped session."""
db = SessionLocal()
try:
yield db
finally:
db.close()
+56
View File
@@ -0,0 +1,56 @@
"""FastAPI dependencies: DB session, token extraction, current user, admin guard.
Copied from Galena (see SHARED.md); only the cookie name differs. In Stage B both apps
read one `core.session` table and the cookie is scoped to the parent domain, which turns
this into real SSO with no new protocol.
"""
from __future__ import annotations
import ipaddress
from fastapi import Depends, Request
from sqlalchemy.orm import Session
from .db import get_db
from .errors import AuthenticationError, AuthorizationError
from .models import AppUser
from .services import auth as auth_service
SESSION_COOKIE = "sygna_session"
def extract_token(request: Request) -> str | None:
"""Authorization: Bearer takes precedence over the session cookie (intentional > ambient)."""
header = request.headers.get("authorization")
if header and header.lower().startswith("bearer "):
token = header[7:].strip()
if token:
return token
return request.cookies.get(SESSION_COOKIE)
def client_ip(request: Request) -> str | None:
host = request.client.host if request.client else None
if not host:
return None
try:
ipaddress.ip_address(host)
except ValueError:
return None
return host
def get_current_user(request: Request, db: Session = Depends(get_db)) -> AppUser:
token = extract_token(request)
if not token:
raise AuthenticationError("Sign in to continue.")
user = auth_service.resolve_session(db, token)
if user is None:
raise AuthenticationError("Your session has expired — please sign in again.")
return user
def require_admin(user: AppUser = Depends(get_current_user)) -> AppUser:
if not user.is_admin:
raise AuthorizationError("This area is for administrators.")
return user
+227
View File
@@ -0,0 +1,227 @@
"""Native PostgreSQL enums, mirrored as Python StrEnums.
The `.value` strings are the canonical DB enum labels. `NodeRole` is ordered
(viewer < editor < approver < manager) — `rank()` exposes that ordering for the authz resolver.
`NodeKind`, `NodeRole`, `PrincipalType` are Galena's, reused unchanged except that NodeKind
gains `matter` (PLAN.md §3.3). Everything below the divider is Sygna's own; none of the names
collide with Galena's, so the two sets can live in one `core` schema at Stage B.
"""
from __future__ import annotations
from enum import StrEnum
# ── shared with Galena — do not diverge ───────────────────────────────────────
class NodeKind(StrEnum):
"""The organizational tree. `matter` is Sygna's leaf, mirroring Galena's `project`."""
workspace = "workspace" # top level — the firm; a permission boundary
group = "group" # a department
folder = "folder" # a team or any grouping
project = "project" # Galena's leaf (a git repo). Never created by Sygna.
matter = "matter" # Sygna's leaf: a case. Its documents live in a Galena project.
class NodeRole(StrEnum):
viewer = "viewer" # read the matter and its file; no time entry
editor = "editor" # record time, add parties, draft documents, create deadlines
approver = "approver" # approve invoices, sign off conflict checks, publish pleadings
manager = "manager" # manage members + permissions on this node and below
@classmethod
def rank(cls, role: "NodeRole | None") -> int:
order = {cls.viewer: 1, cls.editor: 2, cls.approver: 3, cls.manager: 4}
return order.get(role, 0)
class PrincipalType(StrEnum):
"""Who a permission grant is for. `user` now; group is the SSO seam."""
user = "user"
group = "group"
# ── Sygna's own ───────────────────────────────────────────────────────────────
class PartyKind(StrEnum):
person = "person" # osoba fizyczna
organisation = "organisation" # osoba prawna / jednostka organizacyjna
class PartyRole(StrEnum):
"""A party's role IN A MATTER. The same party is a client in one matter and an
opponent in another — which is exactly why conflict checking is not optional."""
client = "client" # klient / mocodawca
opponent = "opponent" # strona przeciwna
opponent_counsel = "opponent_counsel" # pełnomocnik strony przeciwnej
court = "court" # sąd
expert = "expert" # biegły
witness = "witness" # świadek
intervener = "intervener" # interwenient
other = "other"
class PartyRelation(StrEnum):
"""How two parties are linked. Feeds conflict checking beyond exact-name matching."""
parent_company = "parent_company"
subsidiary = "subsidiary"
beneficial_owner = "beneficial_owner"
board_member = "board_member"
spouse = "spouse"
related = "related"
class MatterStatus(StrEnum):
prospect = "prospect" # converted from a lead, not yet opened
open = "open"
suspended = "suspended" # zawieszona
closed = "closed"
archived = "archived"
class FeeType(StrEnum):
hourly = "hourly"
flat = "flat" # ryczałt
capped = "capped"
retainer = "retainer" # abonament
success = "success" # success fee — check KEA/KERP limits before offering
court_appointed = "court_appointed" # z urzędu — billed to the State
pro_bono = "pro_bono"
class DeadlineKind(StrEnum):
procedural = "procedural" # termin procesowy
limitation = "limitation" # przedawnienie / termin zawity
hearing = "hearing" # rozprawa
contractual = "contractual"
internal = "internal"
class DeadlineSource(StrEnum):
"""Where the date came from. `statute` and `court` deadlines are the ones that end
careers, so they carry the dual-confirmation requirement."""
statute = "statute"
court = "court"
contract = "contract"
internal = "internal"
class ConflictOutcome(StrEnum):
pending = "pending"
clear = "clear"
waived = "waived" # conflict found, informed consent obtained
declined = "declined" # instruction refused
class RiskRating(StrEnum):
low = "low"
medium = "medium"
high = "high"
class LeadStage(StrEnum):
new = "new"
qualifying = "qualifying"
proposal = "proposal"
won = "won"
lost = "lost"
class CorrespondenceChannel(StrEnum):
"""How a document reached us. The first two are the ones that carry a legally binding
service date, and the ones Phase 2 automates."""
edoreczenia = "edoreczenia" # e-Doręczenia (UA API v3)
court_portal = "court_portal" # Portal Informacyjny Sądów Powszechnych
post = "post" # poczta tradycyjna
email = "email"
in_person = "in_person" # odebrane osobiście / w biurze podawczym
other = "other"
class CorrespondenceDirection(StrEnum):
incoming = "incoming"
outgoing = "outgoing"
class CorrespondenceStatus(StrEnum):
unassigned = "unassigned" # in the inbox — nobody has said which matter it belongs to
assigned = "assigned"
filed = "filed" # the document is in the matter's Galena case file
ignored = "ignored" # not ours / spam / duplicate, kept for the record
class ExpenseKind(StrEnum):
"""Disbursements (wydatki). `court_fee` and `stamp_duty` are paid to the State and
recharged at cost — see `Expense.is_passthrough`."""
court_fee = "court_fee" # opłata sądowa
stamp_duty = "stamp_duty" # opłata skarbowa
expert = "expert" # biegły
translation = "translation" # tłumaczenie
travel = "travel"
copies = "copies" # odpisy, kopie akt
enforcement = "enforcement" # koszty komornicze
other = "other"
class InvoiceKind(StrEnum):
proforma = "proforma" # faktura pro forma — not a tax document
invoice = "invoice" # faktura VAT
credit_note = "credit_note" # faktura korygująca
class InvoiceStatus(StrEnum):
"""An invoice hardens as it moves right. `issued` is the point of no return: after it,
corrections are a credit note, never an edit."""
draft = "draft"
approved = "approved" # a partner has read the narratives
issued = "issued"
paid = "paid"
cancelled = "cancelled"
class KsefStatus(StrEnum):
"""Where an invoice stands with KSeF. Columns exist now; the connector is Phase 2 work."""
not_sent = "not_sent"
pending = "pending"
accepted = "accepted"
rejected = "rejected"
offline = "offline" # wystawiona w trybie offline24, do wysłania
class DepositMovementKind(StrEnum):
"""Movements on client money held by the firm."""
deposit = "deposit" # wpłata klienta
refund = "refund" # zwrot do klienta
applied = "applied" # zaliczona na fakturę
expense = "expense" # pokrycie wydatku (np. opłaty sądowej)
correction = "correction"
class NotificationKind(StrEnum):
"""Why someone is being told something. Same table shape as Galena's `notification`
(SHARED.md); only the kinds differ, because the two applications notify about
different things."""
deadline_due = "deadline_due" # a termin is approaching
deadline_overdue = "deadline_overdue" # it passed and nothing was recorded
deadline_unconfirmed = "deadline_unconfirmed" # statutory/court, still needs a second person
correspondence_unassigned = "correspondence_unassigned" # sitting in the inbox
service_date_missing = "service_date_missing" # a clock that may already be running
conflict_pending = "conflict_pending" # a check nobody has decided
matter_assigned = "matter_assigned" # you are now responsible for a matter
class Seniority(StrEnum):
"""Grade, for rate cards. Lives on `lawyer_profile` rather than `app_user`, because
`app_user` is byte-identical with Galena's and must stay that way (SHARED.md)."""
partner = "partner"
counsel = "counsel"
senior_associate = "senior_associate"
associate = "associate"
trainee = "trainee" # aplikant
paralegal = "paralegal"
other = "other"
class WallMode(StrEnum):
"""An ethical wall entry. `deny` beats every inherited grant; `allow` re-admits a
named individual to a matter that is otherwise walled off."""
allow = "allow"
deny = "deny"
+104
View File
@@ -0,0 +1,104 @@
"""RFC 9457 Problem Details errors + handlers/middleware.
Copied verbatim from Galena (see SHARED.md) so both applications' clients parse one error
format. Stack traces are hidden when APP_ENV=production. DB DataError maps to 422 (not 500).
"""
from __future__ import annotations
import logging
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from sqlalchemy.exc import DataError, IntegrityError
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from .config import get_settings
log = logging.getLogger("sygna.errors")
settings = get_settings()
_PROBLEM = "application/problem+json"
class AppError(Exception):
status_code = 500
title = "Internal Server Error"
def __init__(self, detail: str | None = None):
self.detail = detail or self.title
super().__init__(self.detail)
class AuthenticationError(AppError):
status_code = 401
title = "Unauthorized"
class AuthorizationError(AppError):
status_code = 403
title = "Forbidden"
class NotFoundError(AppError):
status_code = 404
title = "Not Found"
class ConflictError(AppError):
status_code = 409
title = "Conflict"
class ValidationError(AppError):
status_code = 422
title = "Unprocessable Entity"
class UpstreamError(AppError):
"""A dependency (Galena, a government API) failed. Distinct from our own 500 so the
console can say which side broke and offer a retry."""
status_code = 502
title = "Bad Gateway"
def _problem(status: int, title: str, detail: str, extra: dict | None = None) -> JSONResponse:
body = {"type": "about:blank", "title": title, "status": status, "detail": detail}
if extra:
body.update(extra)
return JSONResponse(status_code=status, content=body, media_type=_PROBLEM)
def install_error_handlers(app: FastAPI) -> None:
@app.exception_handler(AppError)
async def _app_error(_: Request, exc: AppError):
return _problem(exc.status_code, exc.title, exc.detail)
@app.exception_handler(StarletteHTTPException)
async def _http_error(_: Request, exc: StarletteHTTPException):
return _problem(exc.status_code, str(exc.detail) or "Error", str(exc.detail))
@app.exception_handler(RequestValidationError)
async def _validation_error(_: Request, exc: RequestValidationError):
return _problem(422, "Unprocessable Entity", "Request validation failed.",
{"errors": exc.errors()})
@app.exception_handler(DataError)
async def _data_error(_: Request, __: DataError):
return _problem(422, "Unprocessable Entity", "Invalid data for one or more fields.")
@app.exception_handler(IntegrityError)
async def _integrity_error(_: Request, __: IntegrityError):
return _problem(409, "Conflict", "That conflicts with an existing record.")
class ProblemDetailErrorMiddleware(BaseHTTPMiddleware):
"""Last-resort catch for unhandled exceptions → RFC 9457 500 (added INSIDE CORS)."""
async def dispatch(self, request: Request, call_next):
try:
return await call_next(request)
except Exception as exc: # noqa: BLE001
log.exception("Unhandled error")
detail = "An unexpected error occurred." if settings.is_production else str(exc)
return _problem(500, "Internal Server Error", detail)
+2
View File
@@ -0,0 +1,2 @@
"""Outbound integrations. The ONLY place in the codebase that makes an HTTP call
(invariant 8) — Galena today, e-Doręczenia / KSeF / registers in Phase 2."""
+69
View File
@@ -0,0 +1,69 @@
"""Shared plumbing for outbound calls.
Every connector goes through `request()`, so retries, timeouts and error mapping are decided
once. Government APIs are the eventual users of this and they fail in every way an API can, so
the boundary is deliberately narrow: a connector may return data or raise `UpstreamError`, and
nothing else leaks to a service.
"""
from __future__ import annotations
import logging
import time
from typing import Any
import httpx
from ..errors import UpstreamError
log = logging.getLogger("sygna.integrations")
# Retry only what is safe to repeat: transport failures and the server-side 5xx/429 family.
_RETRY_STATUS = frozenset({429, 500, 502, 503, 504})
_BACKOFF_SECONDS = (0.5, 2.0)
def request(
method: str,
url: str,
*,
token: str | None = None,
json: Any = None,
params: dict | None = None,
timeout: float = 15.0,
service: str = "upstream",
) -> httpx.Response:
"""One HTTP call with bounded retries. Raises UpstreamError on give-up."""
headers = {"Accept": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
last_error: str = "no attempt made"
for attempt in range(len(_BACKOFF_SECONDS) + 1):
try:
with httpx.Client(timeout=timeout, follow_redirects=False) as client:
response = client.request(
method, url, headers=headers, json=json, params=params
)
if response.status_code in _RETRY_STATUS:
last_error = f"HTTP {response.status_code}"
else:
return response
except httpx.HTTPError as exc:
last_error = str(exc) or exc.__class__.__name__
if attempt < len(_BACKOFF_SECONDS):
time.sleep(_BACKOFF_SECONDS[attempt])
log.warning("%s: %s — retrying (%d)", service, last_error, attempt + 1)
raise UpstreamError(f"{service} nie odpowiada ({last_error}).")
def problem_detail(response: httpx.Response, fallback: str) -> str:
"""Pull the human-readable message out of an RFC 9457 body, which is what Galena speaks."""
try:
body = response.json()
except ValueError:
return fallback
if isinstance(body, dict):
return str(body.get("detail") or body.get("title") or fallback)
return fallback
+106
View File
@@ -0,0 +1,106 @@
"""Galena — the document store. Each matter's case file (`akta sprawy`) is a Galena project.
Calls carry the ACTING USER's token, never a service account (PLAN.md §3.5). That is the whole
security design: Galena's `authz` stays the single authority on document access, so there is no
privilege-escalation seam between the two applications to defend.
Stage A means Sygna and Galena are separate deployments with separate user directories, so the
user's Sygna token is only accepted by Galena once the two share an identity store. Until then
this connector runs in one of two modes:
- **configured** (`GALENA_BASE_URL` set): try the call; on failure the matter is still created
and `document_node_id` stays NULL, with the reason recorded in the audit log. A case file is
worth retrying for; it is never worth losing a matter over.
- **not configured** (the default): a no-op that returns None, and the console shows
"Brak akt" with an explanation rather than a broken link.
"""
from __future__ import annotations
import logging
import uuid
from ..config import get_settings
from ..errors import UpstreamError
from .base import problem_detail, request
log = logging.getLogger("sygna.integrations.galena")
settings = get_settings()
API = "/api/v1"
def enabled() -> bool:
return settings.galena_enabled
def embed_enabled() -> bool:
"""Stage C: whether the case file may be rendered inside Sygna's own screen.
Requires `GALENA_EMBED=true` AND a known console origin. It stays off by default because
embedding against a Galena that has not had its `frame-ancestors` widened produces a silent
blank frame — a worse experience than the link it replaces."""
return settings.galena_embed and bool(settings.galena_origin)
def case_file_url(document_node_id: uuid.UUID | str | None) -> str | None:
"""Deep link into Galena's console for a case file. Stage C embeds Galena's ReaderJS viewer
same-origin instead; until then a link is honest about being a second application."""
if not document_node_id:
return None
base = settings.galena_console
if not base:
return None
return f"{base}/#/n/{document_node_id}"
def _default_parent(token: str) -> str | None:
"""Where new case files go. Configured id wins; otherwise ask Galena for the acting user's
personal workspace, which every Galena account has."""
configured = settings.galena_casefile_parent_id.strip()
if configured:
return configured
response = request(
"GET", f"{settings.galena_base_url.rstrip('/')}{API}/drive/home",
token=token, timeout=settings.galena_timeout_seconds, service="Galena",
)
if response.status_code != 200:
raise UpstreamError(problem_detail(response, "Galena odrzuciła żądanie."))
return response.json().get("personal_id")
def create_case_file(token: str, *, name: str, parent_id: str | None = None) -> uuid.UUID | None:
"""Create the matter's Galena project. Returns its node id, or None if Galena is off."""
if not enabled():
return None
base = settings.galena_base_url.rstrip("/")
parent = parent_id or _default_parent(token)
response = request(
"POST", f"{base}{API}/nodes",
token=token,
json={"parent_id": parent, "kind": "project", "name": name},
timeout=settings.galena_timeout_seconds,
service="Galena",
)
if response.status_code not in (200, 201):
raise UpstreamError(problem_detail(response, "Galena nie utworzyła akt sprawy."))
node_id = response.json().get("id")
if not node_id:
raise UpstreamError("Galena zwróciła odpowiedź bez identyfikatora akt.")
return uuid.UUID(str(node_id))
def try_create_case_file(token: str | None, *, name: str) -> tuple[uuid.UUID | None, str | None]:
"""Best-effort wrapper used when opening a matter.
Returns (node_id, error_message). A failure is reported, never raised: losing the case file
is recoverable (retry from the matter screen), losing the matter is not."""
if not enabled() or not token:
return None, None
try:
return create_case_file(token, name=name), None
except UpstreamError as exc:
log.warning("Case file not created for %r: %s", name, exc.detail)
return None, exc.detail
except Exception as exc: # noqa: BLE001 — a connector must never break matter creation
log.exception("Unexpected error creating case file for %r", name)
return None, str(exc)
+77
View File
@@ -0,0 +1,77 @@
"""Public register lookups: KRS and the Biała lista wykaz podatników VAT.
Both are free and need no credentials, which is why they are the registers Sygna reaches for
first. Everything goes through `integrations.base.request`, so retries, timeouts and error
mapping are decided in one place (invariant 8).
Verified against the live services on 2026-08-13: `api-krs.ms.gov.pl` answers with RFC 7807
problem details on a miss, and `wl-api.mf.gov.pl` returns the subject plus its bank accounts.
Both are government endpoints and both will move eventually; the mapping lives in
`services/registers.py` so a change there is a fixture update, not a rewrite.
"""
from __future__ import annotations
import datetime as dt
import logging
from ..config import get_settings
from ..errors import NotFoundError, UpstreamError
from ..services import registers as mapping
from .base import request
log = logging.getLogger("sygna.integrations.registers")
settings = get_settings()
KRS_BASE = "https://api-krs.ms.gov.pl/api/krs/OdpisAktualny"
VAT_BASE = "https://wl-api.mf.gov.pl/api/search/nip"
TIMEOUT = 20.0
def krs_lookup(krs: str, registry: str = "P") -> dict:
"""Fetch an OdpisAktualny. `registry` is P (przedsiębiorcy) or S (stowarzyszenia).
A number can legitimately exist in one register and not the other, so a miss in P retries
in S before giving up — otherwise every foundation and association looks like a bad number.
"""
number = mapping.clean_krs(krs)
tried = [registry] + [r for r in mapping.KRS_REGISTRIES if r != registry]
for reg in tried:
response = request(
"GET", f"{KRS_BASE}/{number}",
params={"rejestr": reg, "format": "json"},
timeout=TIMEOUT, service="KRS",
)
if response.status_code == 200:
data = mapping.normalize_krs(response.json())
data["registry"] = reg
return data
if response.status_code != 404:
raise UpstreamError(f"KRS odpowiedział błędem {response.status_code}.")
raise NotFoundError(f"Nie znaleziono podmiotu o numerze KRS {number}.")
def vat_lookup(nip: str, on_date: dt.date | None = None) -> dict:
"""Check a NIP against the Biała lista on a given date (default: today).
The date matters: the register answers "was this taxpayer active on that day", which is the
question that decides whether a supplier invoice is deductible."""
number = mapping.clean_nip(nip)
if not mapping.nip_checksum_ok(number):
# Fail here rather than at the API — a wrong check digit is a typo, and saying so is
# more useful than "not found".
raise UpstreamError(f"NIP {number} ma nieprawidłową sumę kontrolną — sprawdź wpis.")
on_date = on_date or dt.date.today()
response = request(
"GET", f"{VAT_BASE}/{number}",
params={"date": on_date.isoformat()},
timeout=TIMEOUT, service="Biała lista",
)
if response.status_code == 404:
raise NotFoundError(f"Nie znaleziono podatnika o numerze NIP {number}.")
if response.status_code != 200:
raise UpstreamError(f"Biała lista odpowiedziała błędem {response.status_code}.")
data = mapping.normalize_vat(response.json())
data["checked_on"] = on_date.isoformat()
if not data.get("found"):
raise NotFoundError(f"Nie znaleziono podatnika o numerze NIP {number}.")
return data
+14
View File
@@ -0,0 +1,14 @@
"""Minimal logging configuration."""
from __future__ import annotations
import logging
def configure_logging() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
)
# Quiet noisy libraries.
logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
+148
View File
@@ -0,0 +1,148 @@
"""FastAPI application entrypoint."""
from __future__ import annotations
import asyncio
import contextlib
import os
from collections.abc import AsyncIterator
from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from . import __version__
from .config import get_settings
from .db import engine
from .errors import ProblemDetailErrorMiddleware, install_error_handlers
from .logging_config import configure_logging
from .observability import setup_observability
from .routers import (
admin,
auth,
billing,
conflicts,
correspondence,
dashboard,
deadlines,
fees,
health,
intake,
matters,
nodes,
notifications,
parties,
permissions,
rates,
registers,
reports,
timelog,
users,
)
from .services import reminders
API_PREFIX = "/api/v1"
settings = get_settings()
configure_logging()
@contextlib.asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
"""Start the reminder scheduler on startup, cancel it on shutdown. It is a no-op when
REMINDERS_ENABLED is false, so this is always safe to run."""
task = asyncio.create_task(reminders.scheduler_loop())
try:
yield
finally:
task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await task
app = FastAPI(
title="Sygna API",
version=__version__,
description="Backend for Sygna — practice management for Polish law firms.",
docs_url=f"{API_PREFIX}/docs",
redoc_url=None,
openapi_url=f"{API_PREFIX}/openapi.json",
lifespan=lifespan,
)
install_error_handlers(app)
setup_observability(app, engine)
# Added BEFORE CORS so 500s flow back out through CORS and carry the headers a browser needs.
app.add_middleware(ProblemDetailErrorMiddleware)
if settings.cors_origins_list:
if "*" in settings.cors_origins_list:
raise RuntimeError("CORS_ALLOW_ORIGINS='*' is unsafe with credentialed CORS.")
app.add_middleware(
CORSMiddleware, allow_origins=settings.cors_origins_list, allow_credentials=True,
allow_methods=["*"], allow_headers=["*"],
)
# Content-Security-Policy for the console. 'unsafe-inline' is required by the theme pre-paint
# inline <script> and the inline style="" attributes in index.html. Nothing loads from a CDN —
# Sygna's console is entirely same-origin, which is the point when the data is privileged.
#
# `frame-src` names Galena's origin ONLY when embedding is switched on, so the default build
# still frames nothing at all. Stage C (PLAN.md §3.4) needs the matching change on Galena's
# side; until that lands the console falls back to a link.
_FRAME_SRC = "'self'"
if settings.galena_embed and settings.galena_origin:
_FRAME_SRC = f"'self' {settings.galena_origin}"
_CONSOLE_CSP = (
"default-src 'self'; "
"base-uri 'self'; "
"object-src 'none'; "
"frame-ancestors 'none'; "
f"frame-src {_FRAME_SRC}; "
"form-action 'self'; "
"img-src 'self' data: blob:; "
"font-src 'self' data:; "
"style-src 'self' 'unsafe-inline'; "
"script-src 'self' 'unsafe-inline'; "
"connect-src 'self'"
)
@app.middleware("http")
async def _security_headers(request, call_next):
"""Revalidate the static console (no-cache → conditional GET, so a rebuilt app.js/app.css is
picked up without a hard refresh) and attach security headers."""
resp = await call_next(request)
resp.headers.setdefault("X-Content-Type-Options", "nosniff")
resp.headers.setdefault("Referrer-Policy", "same-origin")
resp.headers.setdefault("Cross-Origin-Opener-Policy", "same-origin")
resp.headers.setdefault("X-Frame-Options", "DENY")
path = request.url.path
if not path.startswith(("/api", "/healthz")):
resp.headers.setdefault("Cache-Control", "no-cache")
resp.headers.setdefault("Content-Security-Policy", _CONSOLE_CSP)
return resp
for router in (
health.router, auth.router, users.router, admin.router, nodes.router, permissions.router,
parties.router, conflicts.router, intake.router, matters.router, deadlines.router,
correspondence.router, timelog.router, billing.router, fees.router, rates.router,
registers.router, reports.router, notifications.router, dashboard.router,
):
app.include_router(router, prefix=API_PREFIX)
@app.get("/healthz")
def healthz() -> dict:
return {"status": "ok"}
# Serve the static console (so the app runs without a separate web server in dev). In production
# Caddy can serve it directly. Mount LAST so /api/v1/* and /healthz win.
_FRONTEND = Path(os.environ.get("SYGNA_FRONTEND_DIR")
or Path(__file__).resolve().parents[2] / "frontend")
if _FRONTEND.exists():
app.mount("/", StaticFiles(directory=str(_FRONTEND), html=True), name="frontend")
+51
View File
@@ -0,0 +1,51 @@
"""ORM models — import all so Base.metadata is complete for Alembic and create_all."""
from __future__ import annotations
from .base import Base
from .billing import ClientDeposit, DepositMovement, Expense, Invoice, InvoiceLine
from .conflict import ConflictCheck, Lead
from .correspondence import Correspondence
from .deadline import CourtEvent, Deadline
from .identity import AppSetting, AppUser, AuditLog, Session
from .matter import EthicalWall, Matter, MatterParty
from .node import Favorite, Node, PermissionGrant
from .notification import Notification, NotificationPref
from .party import Party, PartyAlias, PartyLink
from .rate import LawyerProfile, RateCard, RateCardEntry
from .timelog import TimeEntry
__all__ = [
"Base",
# shared with Galena
"AppUser",
"Session",
"AppSetting",
"AuditLog",
"Node",
"PermissionGrant",
"Favorite",
# Sygna
"Party",
"PartyAlias",
"PartyLink",
"Matter",
"MatterParty",
"EthicalWall",
"ConflictCheck",
"Lead",
"Correspondence",
"Deadline",
"CourtEvent",
"Notification",
"NotificationPref",
"LawyerProfile",
"RateCard",
"RateCardEntry",
"TimeEntry",
# money
"Expense",
"Invoice",
"InvoiceLine",
"ClientDeposit",
"DepositMovement",
]
+38
View File
@@ -0,0 +1,38 @@
"""Declarative base + shared column mixins."""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import DateTime, MetaData, Uuid, func, text
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
# Predictable constraint/index names → clean Alembic diffs.
NAMING_CONVENTION = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
class Base(DeclarativeBase):
metadata = MetaData(naming_convention=NAMING_CONVENTION)
class UUIDPkMixin:
id: Mapped[uuid.UUID] = mapped_column(
Uuid(as_uuid=True),
primary_key=True,
server_default=text("gen_random_uuid()"),
)
class TimestampMixin:
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
updated_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()
)
+225
View File
@@ -0,0 +1,225 @@
"""Disbursements, invoices, and client money.
Three rules shape these tables:
- **Integer grosze everywhere** (invariant 12). No float touches an amount.
- **An issued invoice is immutable.** `issued` is the point of no return: a mistake becomes a
credit note (`faktura korygująca`), never an edit. That is not fastidiousness — an invoice is
a tax document, and rewriting one that has left the building is a different kind of problem.
- **Client money is not firm money.** Deposits live on their own ledger with a balance that
cannot go negative, enforced by a CHECK constraint rather than by remembering to look.
VAT: legal services in Poland are standard-rated, but a court fee recharged at cost is a
pass-through rather than a supply. `Expense.is_passthrough` marks those, and they land on an
invoice outside the VAT base. **The VAT treatment of disbursements needs an accountant's
sign-off before anyone files a return on it** — the same caveat as the fee schedules.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import (
Boolean,
CheckConstraint,
Date,
DateTime,
ForeignKey,
Index,
Integer,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import (
DepositMovementKind,
ExpenseKind,
InvoiceKind,
InvoiceStatus,
KsefStatus,
)
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import pg_enum
class Expense(UUIDPkMixin, TimestampMixin, Base):
"""A disbursement paid on a matter, usually recharged to the client."""
__tablename__ = "expense"
matter_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("matter.id", ondelete="CASCADE"), nullable=False
)
kind: Mapped[ExpenseKind] = mapped_column(pg_enum(ExpenseKind, "expense_kind"),
nullable=False)
spent_on: Mapped[dt.date] = mapped_column(Date, nullable=False)
description: Mapped[str] = mapped_column(Text, nullable=False)
amount_minor: Mapped[int] = mapped_column(Integer, nullable=False)
# Recharged to the client at cost with no VAT of our own added — a court fee is not our
# supply. Set automatically for court fees and stamp duty; overridable.
is_passthrough: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("true")
)
billable: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
# Paid out of client money already held, rather than by the firm.
paid_from_deposit: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
supplier: Mapped[str | None] = mapped_column(Text)
document_ref: Mapped[str | None] = mapped_column(Text) # numer faktury/pokwitowania
invoice_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("invoice.id", ondelete="SET NULL")
)
created_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
__table_args__ = (
CheckConstraint("amount_minor > 0", name="amount_positive"),
Index("ix_expense_matter_id", "matter_id"),
Index("ix_expense_invoice_id", "invoice_id"),
Index("ix_expense_spent_on", "spent_on"),
)
class Invoice(UUIDPkMixin, TimestampMixin, Base):
__tablename__ = "invoice"
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)
kind: Mapped[InvoiceKind] = mapped_column(
pg_enum(InvoiceKind, "invoice_kind"), nullable=False,
server_default=InvoiceKind.invoice.value,
)
status: Mapped[InvoiceStatus] = mapped_column(
pg_enum(InvoiceStatus, "invoice_status"), nullable=False,
server_default=InvoiceStatus.draft.value,
)
# NULL until issued: a draft has no number, because a gap in an invoice sequence is a
# question from the tax office.
number: Mapped[str | None] = mapped_column(Text, unique=True)
issued_on: Mapped[dt.date | None] = mapped_column(Date)
sold_on: Mapped[dt.date | None] = mapped_column(Date) # data sprzedaży
due_on: Mapped[dt.date | None] = mapped_column(Date)
paid_on: Mapped[dt.date | None] = mapped_column(Date)
currency: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'PLN'"))
# Totals are stored, not recomputed on read: an issued invoice must always render exactly
# the figures that were issued, even if a line is later reinterpreted.
net_minor: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
vat_minor: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
gross_minor: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
paid_minor: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
note: Mapped[str | None] = mapped_column(Text)
# A credit note points at what it corrects.
corrects_invoice_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("invoice.id", ondelete="RESTRICT")
)
# KSeF. Columns now so Phase 2's connector is additive; nothing writes them yet.
ksef_status: Mapped[KsefStatus] = mapped_column(
pg_enum(KsefStatus, "ksef_status"), nullable=False,
server_default=KsefStatus.not_sent.value,
)
ksef_number: Mapped[str | None] = mapped_column(Text)
ksef_sent_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
created_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
approved_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
approved_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
__table_args__ = (
CheckConstraint("paid_minor >= 0", name="paid_not_negative"),
Index("ix_invoice_matter_id", "matter_id"),
Index("ix_invoice_client_party_id", "client_party_id"),
Index("ix_invoice_status", "status"),
Index("ix_invoice_issued_on", "issued_on"),
)
class InvoiceLine(UUIDPkMixin, Base):
"""One line on an invoice.
Lines are a SNAPSHOT. The time entries and expenses they were built from keep pointing at
the invoice, but the line carries its own text and amounts — so an invoice reprinted in
three years still says what it said, whatever happened to the underlying records."""
__tablename__ = "invoice_line"
invoice_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("invoice.id", ondelete="CASCADE"), nullable=False
)
position: Mapped[int] = mapped_column(Integer, nullable=False)
description: Mapped[str] = mapped_column(Text, nullable=False)
quantity_milli: Mapped[int] = mapped_column(
Integer, nullable=False, server_default=text("1000")
) # thousandths, so 1.5 h is 1500 — integers all the way down
unit: Mapped[str | None] = mapped_column(Text)
unit_price_minor: Mapped[int] = mapped_column(Integer, nullable=False)
net_minor: Mapped[int] = mapped_column(Integer, nullable=False)
vat_rate: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("23"))
vat_minor: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
gross_minor: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
is_passthrough: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
__table_args__ = (
UniqueConstraint("invoice_id", "position", name="uq_invoice_line_invoice_id_position"),
Index("ix_invoice_line_invoice_id", "invoice_id"),
)
class ClientDeposit(UUIDPkMixin, TimestampMixin, Base):
"""Client money held on account for one matter (zaliczka / depozyt).
One row per matter, carrying a running balance that **cannot go negative** — a CHECK
constraint, not a convention. Poland has no IOLTA regime, but the duty to keep client funds
separate and accounted for is real, and a ledger that can silently overdraw is worthless as
evidence that you did."""
__tablename__ = "client_deposit"
matter_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("matter.id", ondelete="CASCADE"), nullable=False, unique=True
)
currency: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'PLN'"))
balance_minor: Mapped[int] = mapped_column(Integer, nullable=False,
server_default=text("0"))
__table_args__ = (
CheckConstraint("balance_minor >= 0", name="balance_not_negative"),
)
class DepositMovement(UUIDPkMixin, Base):
"""One movement on the deposit ledger. Append-only in practice: a mistake is corrected by
a `correction` movement, so the history reads as what actually happened."""
__tablename__ = "deposit_movement"
deposit_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("client_deposit.id", ondelete="CASCADE"), nullable=False
)
kind: Mapped[DepositMovementKind] = mapped_column(
pg_enum(DepositMovementKind, "deposit_movement_kind"), nullable=False
)
# Signed: positive adds to the balance, negative takes from it.
amount_minor: Mapped[int] = mapped_column(Integer, nullable=False)
balance_after_minor: Mapped[int] = mapped_column(Integer, nullable=False)
description: Mapped[str | None] = mapped_column(Text)
invoice_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("invoice.id", ondelete="SET NULL")
)
expense_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("expense.id", ondelete="SET NULL")
)
created_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
CheckConstraint("amount_minor <> 0", name="amount_nonzero"),
Index("ix_deposit_movement_deposit_id", "deposit_id"),
Index("ix_deposit_movement_created_at", "created_at"),
)
+88
View File
@@ -0,0 +1,88 @@
"""Conflict-of-interest checks and the intake pipeline.
`conflict_check` rows are never edited or deleted (invariant 6). They are the firm's evidence
if a conflict is ever alleged — a mutable record is worth nothing in a disciplinary hearing. To
change an outcome, run a new check that supersedes the old one.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import DateTime, ForeignKey, Index, Integer, Text, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import ConflictOutcome, LeadStage
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import pg_enum
class Lead(UUIDPkMixin, TimestampMixin, Base):
"""An enquiry, before it is a matter. This is the CRM half of the product.
A lead cannot become a matter until a conflict check on it has an outcome of `clear` or
`waived` — enforced in services/matters.py, not by a constraint, because the error message
matters more than the database's opinion."""
__tablename__ = "lead"
name: Mapped[str] = mapped_column(Text, nullable=False)
contact_name: Mapped[str | None] = mapped_column(Text)
email: Mapped[str | None] = mapped_column(Text)
phone: Mapped[str | None] = mapped_column(Text)
source: Mapped[str | None] = mapped_column(Text) # polecenie, strona www, ranking…
practice_area: Mapped[str | None] = mapped_column(Text)
summary: Mapped[str | None] = mapped_column(Text)
adverse_names: Mapped[str | None] = mapped_column(Text) # who the enquiry is against
estimated_value_minor: Mapped[int | None] = mapped_column(Integer)
stage: Mapped[LeadStage] = mapped_column(
pg_enum(LeadStage, "lead_stage"), nullable=False, server_default=LeadStage.new.value
)
owner_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
party_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("party.id", ondelete="SET NULL"))
matter_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("matter.id", ondelete="SET NULL")
)
lost_reason: Mapped[str | None] = mapped_column(Text)
__table_args__ = (
Index("ix_lead_stage", "stage"),
Index("ix_lead_owner_id", "owner_id"),
)
class ConflictCheck(UUIDPkMixin, Base):
__tablename__ = "conflict_check"
# What was searched: the proposed client and opposing names, as typed at intake.
subject: Mapped[str] = mapped_column(Text, nullable=False)
adverse_names: Mapped[str | None] = mapped_column(Text)
# Frozen snapshot of every hit, so the record still reads correctly after parties change.
hits: Mapped[list | None] = mapped_column(JSONB)
hit_count: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
outcome: Mapped[ConflictOutcome] = mapped_column(
pg_enum(ConflictOutcome, "conflict_outcome"), nullable=False,
server_default=ConflictOutcome.pending.value,
)
decision_note: Mapped[str | None] = mapped_column(Text)
lead_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("lead.id", ondelete="SET NULL"))
# Set once the check clears and a matter is opened from it.
matter_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("matter.id", ondelete="SET NULL")
)
run_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
decided_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
decided_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
Index("ix_conflict_check_matter_id", "matter_id"),
Index("ix_conflict_check_lead_id", "lead_id"),
Index("ix_conflict_check_created_at", "created_at"),
)
+90
View File
@@ -0,0 +1,90 @@
"""Correspondence — every document in or out, and the clock it starts.
This table is the seam. Today it is filled by hand; in Phase 2 the e-Doręczenia and Portal
Informacyjny connectors write exactly the same rows, and nothing downstream changes. That is
why it exists now rather than alongside the connectors: the expensive part is not fetching a
document, it is deciding what a service date means and making every derived deadline point back
at it.
`legal_service_date` is the field the whole product turns on. It is not "when we noticed" —
it is the date the law says delivery occurred, which is what every procedural deadline counts
from. `received_at` is the separate, boring fact of when the row appeared in our system.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import (
Date,
DateTime,
ForeignKey,
Index,
Text,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import CorrespondenceChannel, CorrespondenceDirection, CorrespondenceStatus
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import pg_enum
class Correspondence(UUIDPkMixin, TimestampMixin, Base):
__tablename__ = "correspondence"
# NULL = still in the inbox. Assigning it to a matter is a deliberate human act, because
# guessing wrong here attaches a court letter to the wrong client's file.
matter_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("matter.id", ondelete="SET NULL")
)
channel: Mapped[CorrespondenceChannel] = mapped_column(
pg_enum(CorrespondenceChannel, "correspondence_channel"), nullable=False
)
direction: Mapped[CorrespondenceDirection] = mapped_column(
pg_enum(CorrespondenceDirection, "correspondence_direction"), nullable=False,
server_default=CorrespondenceDirection.incoming.value,
)
status: Mapped[CorrespondenceStatus] = mapped_column(
pg_enum(CorrespondenceStatus, "correspondence_status"), nullable=False,
server_default=CorrespondenceStatus.unassigned.value,
)
subject: Mapped[str] = mapped_column(Text, nullable=False)
sender: Mapped[str | None] = mapped_column(Text)
recipient: Mapped[str | None] = mapped_column(Text)
note: Mapped[str | None] = mapped_column(Text)
# THE field. Set once and never inferred (invariant 7). Nullable because outgoing post has
# no service date on our side, and because an item can sit in the inbox before anyone has
# established when it was served.
legal_service_date: Mapped[dt.date | None] = mapped_column(Date)
# When the row appeared here — an operational fact, not a legal one. Never count from this.
received_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
sent_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
# The upstream system's identifier: an e-Doręczenia EPO/EPD id, a Portal Informacyjny
# document id, a registered-post tracking number. Unique per channel where present, so a
# connector that re-polls cannot create the same item twice.
external_ref: Mapped[str | None] = mapped_column(Text)
# Where the document lives inside the matter's Galena case file, e.g. "pisma/2026-08-13-sprzeciw.pdf".
document_path: Mapped[str | None] = mapped_column(Text)
created_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
assigned_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
assigned_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
__table_args__ = (
Index("ix_correspondence_matter_id", "matter_id"),
Index("ix_correspondence_status", "status"),
Index("ix_correspondence_legal_service_date", "legal_service_date"),
# Partial unique index: idempotent ingestion for connectors, no constraint on the
# hand-entered items that have no upstream identifier.
Index(
"uq_correspondence_channel_external_ref",
"channel", "external_ref",
unique=True,
postgresql_where=text("external_ref IS NOT NULL"),
),
)
+82
View File
@@ -0,0 +1,82 @@
"""Deadlines (terminy) and court events (rozprawy).
The one part of the system where a bug is malpractice rather than an inconvenience, so:
- `legal_service_date` on the source correspondence is the only clock start, and a derived
deadline always points back at the row it came from (invariant 7);
- statutory and court deadlines require confirmation by a second person before they count as
managed — `confirmed_by_id` is a column, not a convention.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Index, Text, text
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import DeadlineKind, DeadlineSource
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import pg_enum
class Deadline(UUIDPkMixin, TimestampMixin, Base):
__tablename__ = "deadline"
matter_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("matter.id", ondelete="CASCADE"), nullable=False
)
title: Mapped[str] = mapped_column(Text, nullable=False)
kind: Mapped[DeadlineKind] = mapped_column(
pg_enum(DeadlineKind, "deadline_kind"), nullable=False
)
source: Mapped[DeadlineSource] = mapped_column(
pg_enum(DeadlineSource, "deadline_source"), nullable=False
)
due_date: Mapped[dt.date] = mapped_column(Date, nullable=False)
# How this date was reached, in words a lawyer can audit: "doręczenie 2026-08-03 + 14 dni".
basis: Mapped[str | None] = mapped_column(Text)
# The correspondence row whose legal_service_date started the clock. RESTRICT, not SET NULL:
# a deadline that has lost the document proving where its date came from is worse than one
# that blocks a delete. Delete the deadline first, on purpose.
source_correspondence_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("correspondence.id", ondelete="RESTRICT")
)
owner_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
# Dual control: for statutory and court deadlines the confirmer must not be the creator,
# so both ends of the four-eyes rule are recorded, not just the second one.
created_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
confirmed_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
confirmed_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
completed_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
completed_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
notes: Mapped[str | None] = mapped_column(Text)
__table_args__ = (
Index("ix_deadline_matter_id", "matter_id"),
Index("ix_deadline_due_date", "due_date"),
Index("ix_deadline_owner_id", "owner_id"),
)
class CourtEvent(UUIDPkMixin, TimestampMixin, Base):
"""A hearing or other diarised court appearance."""
__tablename__ = "court_event"
matter_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("matter.id", ondelete="CASCADE"), nullable=False
)
title: Mapped[str] = mapped_column(Text, nullable=False)
starts_at: Mapped[dt.datetime] = mapped_column(DateTime(timezone=True), nullable=False)
court: Mapped[str | None] = mapped_column(Text)
room: Mapped[str | None] = mapped_column(Text)
attending_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
is_remote: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
notes: Mapped[str | None] = mapped_column(Text)
__table_args__ = (
Index("ix_court_event_matter_id", "matter_id"),
Index("ix_court_event_starts_at", "starts_at"),
)
+112
View File
@@ -0,0 +1,112 @@
"""Identity, sessions, instance settings, audit log."""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, Text, Uuid, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import SafeInet
class AppUser(UUIDPkMixin, TimestampMixin, Base):
__tablename__ = "app_user"
email: Mapped[str] = mapped_column(Text, nullable=False)
# Nullable so externally-authenticated (SSO/LDAP) accounts can exist without a local password.
password_hash: Mapped[str | None] = mapped_column(Text) # Argon2id
full_name: Mapped[str] = mapped_column(Text, nullable=False)
# Instance administrator: manages users + every workspace, opens the Administration screen.
is_admin: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
failed_login_count: Mapped[int] = mapped_column(
Integer, nullable=False, server_default=text("0")
)
locked_until: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
__table_args__ = (Index("uq_app_user_email_lower", text("lower(email)"), unique=True),)
class Session(UUIDPkMixin, Base):
"""A credential. Two kinds share this table (see `kind`):
* `session` — an interactive login. Fixed lifetime (SESSION_TTL_HOURS), no renewal.
* `app_token` — a named credential for a desktop/CLI client, with an *idle* expiry that slides
forward while it is being used. An exfiltrated token that is never used therefore dies on its
own, which a password never does.
Sharing the table is deliberate: `resolve_session` and `revoke_user_sessions` then cover both
without change, so a password change revokes app tokens too — the containment behaviour you
want, and easy to get wrong if the two lived apart.
"""
__tablename__ = "session"
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), nullable=False
)
token_hash: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
expires_at: Mapped[dt.datetime] = mapped_column(DateTime(timezone=True), nullable=False)
revoked_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
last_seen_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
created_ip: Mapped[str | None] = mapped_column(SafeInet)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
# ── app tokens (see enums.SessionKind / enums.TokenScope; Text, not native enums) ──
kind: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'session'"))
# User-facing label, e.g. "GalenaConnect on ROMAN-LAPTOP" — what makes revocation targeted
# rather than "sign out everywhere".
name: Mapped[str | None] = mapped_column(Text)
scope: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'read_write'"))
# Idle window in days: on use, expires_at slides to now + this. NULL for login sessions, which
# keep their fixed expiry.
idle_days: Mapped[int | None] = mapped_column(Integer)
# Non-secret head of the token (e.g. "galena_pat_a1b2c3") so a user can tell their tokens apart
# in a list. Stored in the clear on purpose — it identifies, it does not authenticate.
token_prefix: Mapped[str | None] = mapped_column(Text)
__table_args__ = (
Index("ix_session_user_id", "user_id"),
Index("ix_session_expires_at", "expires_at"),
Index("ix_session_user_kind", "user_id", "kind"),
)
class AppSetting(Base):
"""Instance config as auditable key/value."""
__tablename__ = "app_setting"
key: Mapped[str] = mapped_column(Text, primary_key=True)
value: Mapped[str] = mapped_column(Text, nullable=False)
updated_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
class AuditLog(UUIDPkMixin, Base):
"""Append-only. The `app` DB role holds INSERT/SELECT only (enforced in migration)."""
__tablename__ = "audit_log"
actor_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
action: Mapped[str] = mapped_column(String(120), nullable=False)
entity_type: Mapped[str] = mapped_column(String(80), nullable=False)
entity_id: Mapped[uuid.UUID | None] = mapped_column(Uuid(as_uuid=True))
detail: Mapped[str | None] = mapped_column(Text)
ip: Mapped[str | None] = mapped_column(SafeInet)
result: Mapped[str | None] = mapped_column(String(20))
request_id: Mapped[str | None] = mapped_column(String(64))
diff: Mapped[dict | None] = mapped_column(JSONB)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
Index("ix_audit_log_entity", "entity_type", "entity_id"),
Index("ix_audit_log_actor_id", "actor_id"),
Index("ix_audit_log_created_at", "created_at"),
)
+147
View File
@@ -0,0 +1,147 @@
"""Matters (sprawy) — the aggregate root — plus their parties and ethical walls.
A matter is a LEAF of the node tree, mirroring Galena's project rule (PLAN.md §3.1). Its
documents never live here: `document_node_id` points at a Galena project, which is the case
file (`akta sprawy`). In Stage A that is a plain UUID with no FK, because Galena is a separate
database; at Stage B it becomes a real foreign key.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import (
Boolean,
Date,
DateTime,
ForeignKey,
Index,
Integer,
Numeric,
Text,
UniqueConstraint,
Uuid,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import FeeType, MatterStatus, PartyRole, WallMode
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import pg_enum
class Matter(UUIDPkMixin, TimestampMixin, Base):
__tablename__ = "matter"
# Its place in the org tree — a node of kind `matter`. Permissions resolve through this.
node_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("node.id", ondelete="CASCADE"), nullable=False, unique=True
)
# The Galena project holding the case file. NULL = no case file yet (Galena not configured,
# or its creation failed and is pending retry). No FK: cross-database in Stage A.
document_node_id: Mapped[uuid.UUID | None] = mapped_column(Uuid(as_uuid=True))
reference: Mapped[str] = mapped_column(Text, nullable=False, unique=True) # numer sprawy
name: Mapped[str] = mapped_column(Text, nullable=False)
description: Mapped[str | None] = mapped_column(Text)
client_party_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("party.id"), nullable=False)
practice_area: Mapped[str | None] = mapped_column(Text)
status: Mapped[MatterStatus] = mapped_column(
pg_enum(MatterStatus, "matter_status"), nullable=False,
server_default=MatterStatus.open.value,
)
# Responsible = who runs it. Originating = who brought it in (drives credit + reporting).
responsible_lawyer_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
originating_lawyer_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
opened_at: Mapped[dt.date | None] = mapped_column(Date)
closed_at: Mapped[dt.date | None] = mapped_column(Date)
fee_type: Mapped[FeeType] = mapped_column(
pg_enum(FeeType, "fee_type"), nullable=False, server_default=FeeType.hourly.value
)
# Money in integer minor units (grosze) — never a float near an invoice (invariant 12).
# This is the highest-priority OVERRIDE: one rate for everyone on this matter, beating every
# rate card. Leave it NULL and the card hierarchy applies (services/rates.resolve).
default_rate_minor: Mapped[int | None] = mapped_column(Integer)
# Pin a specific card to this matter, e.g. the discounted one agreed to win the pitch.
rate_card_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("rate_card.id", ondelete="SET NULL")
)
fee_cap_minor: Mapped[int | None] = mapped_column(Integer)
currency: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'PLN'"))
# Wartość przedmiotu sporu. Numeric, not int: it drives statutory fee formulas.
value_in_dispute: Mapped[float | None] = mapped_column(Numeric(14, 2))
# Court block
court: Mapped[str | None] = mapped_column(Text)
court_department: Mapped[str | None] = mapped_column(Text)
case_signature: Mapped[str | None] = mapped_column(Text) # sygnatura akt
instance: Mapped[str | None] = mapped_column(Text)
__table_args__ = (
Index("ix_matter_client_party_id", "client_party_id"),
Index("ix_matter_status", "status"),
Index("ix_matter_responsible_lawyer_id", "responsible_lawyer_id"),
Index("ix_matter_case_signature", "case_signature"),
)
class MatterParty(UUIDPkMixin, Base):
"""A party's involvement in a matter. `is_adverse` is what the conflict engine keys on —
it is set from the role but stored, because a role can be re-typed and history must not
silently change what a past conflict check saw."""
__tablename__ = "matter_party"
matter_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("matter.id", ondelete="CASCADE"), nullable=False
)
party_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("party.id"), nullable=False)
role: Mapped[PartyRole] = mapped_column(pg_enum(PartyRole, "party_role"), nullable=False)
is_adverse: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
note: Mapped[str | None] = mapped_column(Text)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
UniqueConstraint("matter_id", "party_id", "role", name="uq_matter_party_matter_id_party"),
Index("ix_matter_party_matter_id", "matter_id"),
Index("ix_matter_party_party_id", "party_id"),
)
class EthicalWall(UUIDPkMixin, Base):
"""An information barrier on one matter for one person.
Role-based access alone cannot express "everyone in the department except Anna" — which is
exactly what a wall is. `deny` beats every inherited grant, including a manager's; `allow`
re-admits a named individual. Instance admins are NOT exempt from a deny: an admin who
needs the file must remove the wall, which leaves an audit trail.
Walls are administered from OUTSIDE the barrier — `services/matters.assert_wall_admin`
authorizes against the matter's parent container. Authorizing it on the matter itself would
let anyone wall themselves out permanently, since the deny also removes their manager role.
"""
__tablename__ = "ethical_wall"
matter_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("matter.id", ondelete="CASCADE"), nullable=False
)
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), nullable=False
)
mode: Mapped[WallMode] = mapped_column(pg_enum(WallMode, "wall_mode"), nullable=False)
reason: Mapped[str | None] = mapped_column(Text)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
__table_args__ = (
UniqueConstraint("matter_id", "user_id", name="uq_ethical_wall_matter_id_user_id"),
Index("ix_ethical_wall_matter_id", "matter_id"),
Index("ix_ethical_wall_user_id", "user_id"),
)
+86
View File
@@ -0,0 +1,86 @@
"""The organizational tree: firm → departments/teams → matters, plus permission grants.
Copied from Galena (see SHARED.md). Galena's `review_policy` / `encryption_mode` columns are
project-only and are omitted here — Sygna never creates a Galena project row, it references one
by id from `matter.document_node_id`.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import DateTime, ForeignKey, Index, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import NodeKind, NodeRole, PrincipalType
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import pg_enum
class Node(UUIDPkMixin, TimestampMixin, Base):
"""A container (workspace/group/folder) or a matter.
`path` is a materialized slug path ("/kancelaria/procesowy/kowalski-sa") used by the authz
resolver for ancestor-or-self prefix matching, and is unique. Top-level nodes (parent_id
NULL) must be workspaces. `personal_owner_id` marks a user's personal workspace.
"""
__tablename__ = "node"
parent_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("node.id", ondelete="CASCADE"))
kind: Mapped[NodeKind] = mapped_column(pg_enum(NodeKind, "node_kind"), nullable=False)
name: Mapped[str] = mapped_column(Text, nullable=False)
slug: Mapped[str] = mapped_column(Text, nullable=False)
path: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
owner_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
personal_owner_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
__table_args__ = (
UniqueConstraint("parent_id", "slug", name="uq_node_parent_id_slug"),
Index("ix_node_parent_id", "parent_id"),
Index("ix_node_kind", "kind"),
Index("ix_node_personal_owner_id", "personal_owner_id"),
)
class PermissionGrant(UUIDPkMixin, Base):
"""A role for a principal on a node. Effective role on any node = the highest grant whose
node is an ancestor-or-self of it (resolved in services/authz.py)."""
__tablename__ = "permission_grant"
node_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("node.id", ondelete="CASCADE"), nullable=False
)
principal_type: Mapped[PrincipalType] = mapped_column(
pg_enum(PrincipalType, "principal_type"), nullable=False,
server_default=PrincipalType.user.value,
)
principal_id: Mapped[uuid.UUID] = mapped_column(nullable=False)
role: Mapped[NodeRole] = mapped_column(pg_enum(NodeRole, "node_role"), nullable=False)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
__table_args__ = (
UniqueConstraint(
"node_id", "principal_type", "principal_id",
name="uq_permission_grant_node_id_principal",
),
Index("ix_permission_grant_node_id", "node_id"),
Index("ix_permission_grant_principal", "principal_type", "principal_id"),
)
class Favorite(Base):
__tablename__ = "favorite"
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), primary_key=True
)
node_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("node.id", ondelete="CASCADE"), primary_key=True
)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
+63
View File
@@ -0,0 +1,63 @@
"""In-app notifications and per-user delivery preferences.
Column shape copied from Galena's `notification` / `notification_pref` (SHARED.md) so the two
tables can merge into one `core` schema at Stage B. Two Sygna-only additions:
- `dedupe_key`, unique per recipient. The reminder scheduler runs daily and would otherwise tell
someone about the same deadline every morning for a fortnight. The key encodes *which
milestone* was announced, so each one is announced exactly once and re-running the scheduler
is safe.
- No `push_subscription` table yet — web push is a delivery channel, and Sygna has nothing to
deliver until the in-app one has proved useful.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Text, UniqueConstraint, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import NotificationKind
from .base import Base, UUIDPkMixin
from .types import pg_enum
class Notification(UUIDPkMixin, Base):
__tablename__ = "notification"
recipient_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), nullable=False
)
kind: Mapped[NotificationKind] = mapped_column(
pg_enum(NotificationKind, "notification_kind"), nullable=False
)
title: Mapped[str] = mapped_column(Text, nullable=False)
body: Mapped[str | None] = mapped_column(Text)
link: Mapped[str | None] = mapped_column(Text)
payload: Mapped[dict | None] = mapped_column(JSONB)
# Idempotency for the scheduler — see the module docstring.
dedupe_key: Mapped[str | None] = mapped_column(Text)
read_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
UniqueConstraint("recipient_id", "dedupe_key",
name="uq_notification_recipient_id_dedupe_key"),
Index("ix_notification_recipient", "recipient_id", "read_at"),
Index("ix_notification_created_at", "created_at"),
)
class NotificationPref(Base):
__tablename__ = "notification_pref"
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), primary_key=True
)
inapp: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
webpush: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
email: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
+96
View File
@@ -0,0 +1,96 @@
"""Parties — clients, opponents, courts, experts, witnesses.
Deliberately ONE table. The same entity is a client in one matter and an opponent in another,
and the conflict engine can only see that if they share a table. `search_key` is the normalised
form the conflict check matches on (see services/conflicts.py).
"""
from __future__ import annotations
import uuid
from sqlalchemy import Boolean, ForeignKey, Index, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import PartyKind, PartyRelation, RiskRating
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import pg_enum
class Party(UUIDPkMixin, TimestampMixin, Base):
__tablename__ = "party"
kind: Mapped[PartyKind] = mapped_column(pg_enum(PartyKind, "party_kind"), nullable=False)
# Display name. For a person, "Nazwisko Imię" order is a UI concern, not a storage one.
name: Mapped[str] = mapped_column(Text, nullable=False)
# Normalised for matching: lowercase, diacritics folded, legal-form suffixes stripped.
search_key: Mapped[str] = mapped_column(Text, nullable=False)
# Polish identifiers. Not unique — the same NIP can legitimately appear twice while a
# duplicate is being merged, and a hard constraint would block intake at the worst moment.
nip: Mapped[str | None] = mapped_column(Text)
pesel: Mapped[str | None] = mapped_column(Text)
krs: Mapped[str | None] = mapped_column(Text)
regon: Mapped[str | None] = mapped_column(Text)
email: Mapped[str | None] = mapped_column(Text)
phone: Mapped[str | None] = mapped_column(Text)
address: Mapped[str | None] = mapped_column(Text)
# e-Doręczenia address (ADE). Populated from BAE in Phase 2.
edoreczenia_address: Mapped[str | None] = mapped_column(Text)
is_pep: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
risk_rating: Mapped[RiskRating] = mapped_column(
pg_enum(RiskRating, "risk_rating"), nullable=False, server_default=RiskRating.low.value
)
notes: Mapped[str | None] = mapped_column(Text)
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
__table_args__ = (
Index("ix_party_search_key", "search_key"),
Index("ix_party_nip", "nip"),
Index("ix_party_krs", "krs"),
)
class PartyAlias(UUIDPkMixin, Base):
"""Former names, trading names, declension stems, transliterations. Every alias is
searched by the conflict engine exactly like the primary name."""
__tablename__ = "party_alias"
party_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("party.id", ondelete="CASCADE"), nullable=False
)
alias: Mapped[str] = mapped_column(Text, nullable=False)
search_key: Mapped[str] = mapped_column(Text, nullable=False)
__table_args__ = (
UniqueConstraint("party_id", "search_key", name="uq_party_alias_party_id_search_key"),
Index("ix_party_alias_search_key", "search_key"),
)
class PartyLink(UUIDPkMixin, Base):
"""A relationship between two parties — group structure, beneficial ownership, family.
The conflict engine walks these one hop out, because acting against a client's parent
company is a conflict even though the names never match."""
__tablename__ = "party_link"
from_party_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("party.id", ondelete="CASCADE"), nullable=False
)
to_party_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("party.id", ondelete="CASCADE"), nullable=False
)
relation: Mapped[PartyRelation] = mapped_column(
pg_enum(PartyRelation, "party_relation"), nullable=False
)
note: Mapped[str | None] = mapped_column(Text)
__table_args__ = (
UniqueConstraint("from_party_id", "to_party_id", "relation",
name="uq_party_link_from_party_id_pair"),
Index("ix_party_link_from_party_id", "from_party_id"),
Index("ix_party_link_to_party_id", "to_party_id"),
)
+120
View File
@@ -0,0 +1,120 @@
"""Rate cards, and the professional details a rate depends on.
Rates are **effective-dated and scoped**, because a real firm has one house rate, a lower one it
agreed with a big client three years ago, and a different one on the matter it took at a
discount to win the relationship. Resolution walks from the most specific scope to the least
(see `services/rates.resolve`) and reports which one it landed on — a lawyer looking at 520 zł
instead of 450 zł needs to be told why, not left to guess.
Nothing here ever rewrites a recorded time entry: `TimeEntry.rate_minor` is a snapshot taken
when the entry is created, so changing a card tomorrow cannot silently re-price yesterday.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import (
Boolean,
CheckConstraint,
Date,
ForeignKey,
Index,
Integer,
Text,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import Seniority
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import pg_enum
class LawyerProfile(UUIDPkMixin, TimestampMixin, Base):
"""Sygna-only professional details for a user.
A separate table on purpose: `app_user` is copied byte-identical from Galena and adding a
column there would break the Stage B merge (SHARED.md)."""
__tablename__ = "lawyer_profile"
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), nullable=False, unique=True
)
seniority: Mapped[Seniority] = mapped_column(
pg_enum(Seniority, "seniority"), nullable=False, server_default=Seniority.other.value
)
# Wpis na listę: numer ORA (adwokaci) lub OIRP (radcowie prawni).
bar_number: Mapped[str | None] = mapped_column(Text)
bar_chamber: Mapped[str | None] = mapped_column(Text)
# Ubezpieczenie OC — obowiązkowe; a lapsed policy is a disciplinary problem, so the expiry
# is worth holding even though nothing acts on it yet.
oc_policy_number: Mapped[str | None] = mapped_column(Text)
oc_valid_to: Mapped[dt.date | None] = mapped_column(Date)
# What an hour of this person costs the firm — salary plus overhead, per hour, in grosze.
# Profitability is meaningless without it, so a matter with any uncosted time reports
# "incomplete" rather than a flattering number computed from zeroes.
cost_rate_minor: Mapped[int | None] = mapped_column(Integer)
class RateCard(UUIDPkMixin, TimestampMixin, Base):
"""A named, effective-dated set of hourly rates.
Scope is by `client_party_id`: NULL means the firm-wide card. A matter can pin one
explicitly via `matter.rate_card_id`."""
__tablename__ = "rate_card"
name: Mapped[str] = mapped_column(Text, nullable=False)
client_party_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("party.id", ondelete="CASCADE")
)
currency: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'PLN'"))
valid_from: Mapped[dt.date] = mapped_column(Date, nullable=False)
valid_to: Mapped[dt.date | None] = mapped_column(Date)
# The firm's house card. At most one may be the default at a time — enforced in the service,
# not by a constraint, because a partial unique index would block the moment of swapping.
is_default: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
note: Mapped[str | None] = mapped_column(Text)
created_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
__table_args__ = (
CheckConstraint("valid_to IS NULL OR valid_to >= valid_from", name="valid_range"),
Index("ix_rate_card_client_party_id", "client_party_id"),
Index("ix_rate_card_valid_from", "valid_from"),
)
class RateCardEntry(UUIDPkMixin, Base):
"""One rate on a card.
Both scoping columns are nullable, and that is the whole design:
- `user_id` set → this person's rate on this card
- `seniority` set → everyone of that grade
- both NULL → the card's fallback rate
Resolution tries them in that order."""
__tablename__ = "rate_card_entry"
rate_card_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("rate_card.id", ondelete="CASCADE"), nullable=False
)
user_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id", ondelete="CASCADE"))
seniority: Mapped[Seniority | None] = mapped_column(pg_enum(Seniority, "seniority"))
rate_minor: Mapped[int] = mapped_column(Integer, nullable=False)
note: Mapped[str | None] = mapped_column(Text)
# Three PARTIAL unique indexes rather than one composite constraint: PostgreSQL treats NULLs
# as distinct in a unique constraint, so `UNIQUE(card, user_id, seniority)` would happily
# allow two fallback rows with both columns NULL — exactly the duplicate that matters.
__table_args__ = (
CheckConstraint("rate_minor > 0", name="rate_positive"),
CheckConstraint("user_id IS NULL OR seniority IS NULL", name="one_scope_only"),
Index("uq_rate_card_entry_user", "rate_card_id", "user_id", unique=True,
postgresql_where=text("user_id IS NOT NULL")),
Index("uq_rate_card_entry_seniority", "rate_card_id", "seniority", unique=True,
postgresql_where=text("seniority IS NOT NULL")),
Index("uq_rate_card_entry_fallback", "rate_card_id", unique=True,
postgresql_where=text("user_id IS NULL AND seniority IS NULL")),
Index("ix_rate_card_entry_rate_card_id", "rate_card_id"),
)
+62
View File
@@ -0,0 +1,62 @@
"""Time entries (karta czasu pracy).
Minutes are stored as an integer and money in integer minor units (grosze) — invariant 12.
The UI works in 0.1 h increments, which is 6 minutes, so every displayed value is exact.
Named `timelog` rather than `time` so the module never shadows the stdlib.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import Boolean, CheckConstraint, Date, ForeignKey, Index, Integer, Text, Uuid, text
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base, TimestampMixin, UUIDPkMixin
class TimeEntry(UUIDPkMixin, TimestampMixin, Base):
__tablename__ = "time_entry"
matter_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("matter.id", ondelete="CASCADE"), nullable=False
)
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("app_user.id"), nullable=False)
work_date: Mapped[dt.date] = mapped_column(Date, nullable=False)
minutes: Mapped[int] = mapped_column(Integer, nullable=False)
# The client reads this. It is not an internal note.
narrative: Mapped[str] = mapped_column(Text, nullable=False)
# UTBMS or a firm's own task code. Free text: international clients mandate their own sets.
activity_code: Mapped[str | None] = mapped_column(Text)
billable: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
# Snapshot of the rate applied, so a later rate-card change never rewrites history.
rate_minor: Mapped[int | None] = mapped_column(Integer)
write_off_minutes: Mapped[int] = mapped_column(
Integer, nullable=False, server_default=text("0")
)
# Set when the entry lands on an invoice. No FK yet — `invoice` arrives in Phase 3 — so
# Phase 3 is additive, matching the deadline/correspondence pattern.
invoice_id: Mapped[uuid.UUID | None] = mapped_column(Uuid(as_uuid=True))
__table_args__ = (
CheckConstraint("minutes > 0", name="minutes_positive"),
CheckConstraint("write_off_minutes >= 0 AND write_off_minutes <= minutes",
name="write_off_within_minutes"),
Index("ix_time_entry_matter_id", "matter_id"),
Index("ix_time_entry_user_id", "user_id"),
Index("ix_time_entry_work_date", "work_date"),
Index("ix_time_entry_invoice_id", "invoice_id"),
)
@property
def billable_minutes(self) -> int:
return 0 if not self.billable else self.minutes - self.write_off_minutes
@property
def amount_minor(self) -> int:
"""Value of this entry in grosze. Integer arithmetic throughout: rate is per hour,
so (minutes * rate) // 60 — rounding down, deliberately, in the client's favour."""
if not self.billable or not self.rate_minor:
return 0
return (self.billable_minutes * self.rate_minor) // 60
+36
View File
@@ -0,0 +1,36 @@
"""Custom SQLAlchemy column types: self-validating INET + native PG enum helper."""
from __future__ import annotations
import ipaddress
from sqlalchemy.dialects.postgresql import ENUM as PGEnum
from sqlalchemy.dialects.postgresql import INET
from sqlalchemy.types import TypeDecorator
class SafeInet(TypeDecorator):
"""An INET column that coerces any non-IP value to NULL on bind, so a bad host
(e.g. Starlette TestClient's literal 'testclient') can never trigger an INET cast error."""
impl = INET
cache_ok = True
def process_bind_param(self, value, dialect):
if value is None:
return None
try:
ipaddress.ip_address(value)
except (ValueError, TypeError):
return None
return value
def pg_enum(py_enum, name: str) -> PGEnum:
# postgresql.ENUM with create_type=False → create_all() never emits CREATE TYPE; the
# Alembic migration's explicit loop is the single source of truth for enum lifecycle.
return PGEnum(
py_enum,
name=name,
create_type=False,
values_callable=lambda enum_cls: [member.value for member in enum_cls],
)
+37
View File
@@ -0,0 +1,37 @@
"""Optional OpenTelemetry wiring. Import-guarded: if the OTel packages are absent, or
OTEL_ENABLED is false, this is a no-op and the app starts normally."""
from __future__ import annotations
import logging
from .config import get_settings
log = logging.getLogger("sygna.observability")
settings = get_settings()
def setup_observability(app, engine) -> None:
if not settings.otel_enabled:
return
try:
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
except ImportError: # pragma: no cover — optional extra
log.warning("OTEL_ENABLED is set but the OpenTelemetry packages are missing; skipping.")
return
provider = TracerProvider(
resource=Resource.create({SERVICE_NAME: settings.otel_service_name})
)
provider.add_span_processor(
BatchSpanProcessor(OTLPSpanExporter(endpoint=settings.otel_exporter_otlp_endpoint))
)
trace.set_tracer_provider(provider)
FastAPIInstrumentor.instrument_app(app)
SQLAlchemyInstrumentor().instrument(engine=engine)
log.info("OpenTelemetry enabled → %s", settings.otel_exporter_otlp_endpoint)
+2
View File
@@ -0,0 +1,2 @@
"""HTTP routers. They validate, authorize, call a service, and serialize — nothing else.
No `select(...)` / `db.add` / `db.execute` here (invariant 2)."""
+77
View File
@@ -0,0 +1,77 @@
"""Administration: instance settings, the full node list, per-user access, integration status."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..config import get_settings
from ..db import get_db
from ..deps import client_ip, require_admin
from ..integrations import galena
from ..models import AppUser
from ..schemas import SettingsIn, node_out
from ..services import audit, authz, nodes
from ..services import settings as settings_svc
router = APIRouter(prefix="/admin", tags=["admin"])
config = get_settings()
@router.get("/settings")
def get_settings_ep(db: Session = Depends(get_db), _: AppUser = Depends(require_admin)):
return settings_svc.all_settings(db)
@router.put("/settings")
def put_settings(body: SettingsIn, request: Request, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
for key, value in body.values.items():
settings_svc.put(db, key, value, actor_id=admin.id)
audit.record(db, actor_id=admin.id, action="settings.update", entity_type="app_setting",
detail=",".join(sorted(body.values)), ip=client_ip(request))
db.commit()
return settings_svc.all_settings(db)
@router.get("/nodes")
def all_nodes(db: Session = Depends(get_db), _: AppUser = Depends(require_admin)):
return [node_out(n) for n in nodes.all_nodes(db)]
@router.get("/users/{user_id}/grants")
def user_grants(user_id: uuid.UUID, db: Session = Depends(get_db),
_: AppUser = Depends(require_admin)):
return [{"node": node_out(node), "role": role.value}
for node, role in authz.grants_for_user(db, user_id)]
@router.delete("/users/{user_id}/grants/{node_id}")
def del_user_grant(user_id: uuid.UUID, node_id: uuid.UUID, request: Request,
db: Session = Depends(get_db), admin: AppUser = Depends(require_admin)):
removed = authz.remove_user_grant(db, node_id, user_id)
if removed:
audit.record(db, actor_id=admin.id, action="access.revoke", entity_type="node",
entity_id=node_id, detail=str(user_id), ip=client_ip(request))
db.commit()
return {"ok": removed}
@router.get("/integrations")
def integrations(request: Request, _: AppUser = Depends(require_admin)):
"""What is wired up. Reports configuration, and probes Galena only when asked to."""
return {
"galena": {
"configured": galena.enabled(),
"base_url": config.galena_base_url or None,
"console_url": config.galena_console or None,
"casefile_parent_id": config.galena_casefile_parent_id or None,
},
"planned": [
{"name": "e-Doręczenia", "phase": 2, "status": "not started"},
{"name": "KSeF 2.0", "phase": 2, "status": "not started"},
{"name": "Rejestry (KRS/CEIDG/Biała lista)", "phase": 2, "status": "not started"},
{"name": "Portal Informacyjny", "phase": 4, "status": "not started"},
],
}
+62
View File
@@ -0,0 +1,62 @@
"""Authentication endpoints — DB-backed cookie sessions. Copied from Galena; see SHARED.md."""
from __future__ import annotations
from fastapi import APIRouter, Depends, Request, Response
from sqlalchemy.orm import Session
from ..config import get_settings
from ..db import get_db
from ..deps import SESSION_COOKIE, client_ip, extract_token, get_current_user
from ..errors import AuthenticationError
from ..models import AppUser
from ..schemas import LoginIn, user_out
from ..services import audit
from ..services import auth as auth_service
router = APIRouter(prefix="/auth", tags=["auth"])
settings = get_settings()
def _cookie_secure(request: Request) -> bool:
"""Whether to set the Secure flag on the session cookie.
Default (SESSION_COOKIE_SECURE unset) is AUTO: Secure only when the request actually
arrived over HTTPS. A Secure cookie sent over plain HTTP is silently dropped by the
browser, which logs the user straight back out on reload. Never key this off APP_ENV."""
if settings.session_cookie_secure is not None:
return settings.session_cookie_secure
return request.url.scheme == "https"
@router.post("/login")
def login(body: LoginIn, request: Request, response: Response, db: Session = Depends(get_db)):
user = auth_service.authenticate(db, body.email, body.password)
if user is None:
audit.record(db, actor_id=None, action="auth.login", entity_type="user",
detail=body.email, result="fail", ip=client_ip(request))
db.commit()
raise AuthenticationError("Nieprawidłowy e-mail lub hasło.")
_session, token = auth_service.create_session(db, user, ip=client_ip(request))
audit.record(db, actor_id=user.id, action="auth.login", entity_type="user",
entity_id=user.id, ip=client_ip(request))
db.commit()
response.set_cookie(
SESSION_COOKIE, token, httponly=True, samesite="lax", secure=_cookie_secure(request),
max_age=settings.session_ttl_hours * 3600, path="/",
)
return {"token": token, "user": user_out(user)}
@router.post("/logout")
def logout(request: Request, response: Response, db: Session = Depends(get_db)):
token = extract_token(request)
if token:
auth_service.revoke_session(db, token)
db.commit()
response.delete_cookie(SESSION_COOKIE, path="/")
return {"ok": True}
@router.get("/me")
def me(user: AppUser = Depends(get_current_user)):
return user_out(user)
+236
View File
@@ -0,0 +1,236 @@
"""Disbursements, invoices and client money.
Reading the numbers needs read access to the matter. Changing them needs `approver` — recording
time is an editor's job, deciding what a client is asked to pay is not.
"""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..enums import NodeRole
from ..models import AppUser
from ..schemas import (
CreditNoteIn,
DepositMoveIn,
DraftInvoiceIn,
ExpenseIn,
IssueIn,
PaymentIn,
deposit_movement_out,
expense_out,
invoice_line_out,
invoice_out,
)
from ..services import audit, billing, matters as matters_svc, parties as parties_svc
router = APIRouter(tags=["billing"])
# ── expenses ──────────────────────────────────────────────────────────────────
@router.get("/matters/{matter_id}/expenses")
def list_expenses(matter_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
matter = matters_svc.get_matter(db, matter_id)
matters_svc.assert_can_read(db, user, matter)
return [expense_out(e) for e in billing.expenses_for(db, matter)]
@router.post("/matters/{matter_id}/expenses")
def add_expense(matter_id: uuid.UUID, body: ExpenseIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters_svc.get_matter(db, matter_id)
matters_svc.assert_role(db, user, matter, NodeRole.editor)
fields = body.model_dump(exclude={"kind", "description", "amount_minor", "spent_on",
"billable", "is_passthrough", "paid_from_deposit"})
row = billing.add_expense(
db, user, matter, kind=body.kind, description=body.description,
amount_minor=body.amount_minor, spent_on=body.spent_on, billable=body.billable,
is_passthrough=body.is_passthrough, paid_from_deposit=body.paid_from_deposit,
**fields,
)
audit.record(db, actor_id=user.id, action="expense.add", entity_type="matter",
entity_id=matter.id,
detail=f"{row.kind.value} {row.amount_minor / 100:.2f} — {row.description[:50]}",
ip=client_ip(request))
db.commit()
return expense_out(row)
@router.delete("/expenses/{expense_id}")
def delete_expense(expense_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
row = billing.get_expense(db, expense_id)
matter = matters_svc.get_matter(db, row.matter_id)
matters_svc.assert_role(db, user, matter, NodeRole.editor)
billing.delete_expense(db, row)
db.commit()
return {"ok": True}
# ── client money ──────────────────────────────────────────────────────────────
@router.get("/matters/{matter_id}/deposit")
def get_deposit(matter_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
matter = matters_svc.get_matter(db, matter_id)
matters_svc.assert_can_read(db, user, matter)
deposit = billing.deposit_for(db, matter)
return {
"balance_minor": deposit.balance_minor if deposit else 0,
"currency": deposit.currency if deposit else matter.currency,
"movements": [deposit_movement_out(m) for m in billing.movements(db, deposit)]
if deposit else [],
}
@router.post("/matters/{matter_id}/deposit")
def move_deposit(matter_id: uuid.UUID, body: DepositMoveIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters_svc.get_matter(db, matter_id)
billing.assert_can_bill(db, user, matter)
row = billing.move_deposit(db, user, matter, amount_minor=body.amount_minor,
kind=body.kind, description=body.description)
audit.record(db, actor_id=user.id, action="deposit.move", entity_type="matter",
entity_id=matter.id,
detail=f"{body.kind.value} {body.amount_minor / 100:.2f} "
f"→ saldo {row.balance_after_minor / 100:.2f}",
ip=client_ip(request))
db.commit()
return deposit_movement_out(row)
# ── invoices ──────────────────────────────────────────────────────────────────
@router.get("/matters/{matter_id}/billing")
def matter_billing(matter_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
"""Everything the matter's money tab needs in one call."""
matter = matters_svc.get_matter(db, matter_id)
matters_svc.assert_can_read(db, user, matter)
entries, costs = billing.unbilled(db, matter)
return {
"financials": billing.matter_financials(db, matter),
"invoices": [invoice_out(i, matter=matter) for i in billing.for_matter(db, matter)],
"unbilled": {
"minutes": sum(e.billable_minutes for e in entries),
"time_minor": sum(e.amount_minor for e in entries),
"expenses_minor": sum(c.amount_minor for c in costs),
"entries": len(entries),
"expense_rows": len(costs),
},
}
@router.post("/matters/{matter_id}/invoices")
def draft_invoice(matter_id: uuid.UUID, body: DraftInvoiceIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters_svc.get_matter(db, matter_id)
billing.assert_can_bill(db, user, matter)
invoice = billing.draft_from_unbilled(
db, user, matter, group_time=body.group_time, vat_rate=body.vat_rate, note=body.note
)
audit.record(db, actor_id=user.id, action="invoice.draft", entity_type="matter",
entity_id=matter.id, detail=f"{invoice.gross_minor / 100:.2f} brutto",
ip=client_ip(request))
db.commit()
return invoice_out(invoice, matter=matter)
@router.get("/invoices/{invoice_id}")
def get_invoice(invoice_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
invoice = billing.get_invoice(db, invoice_id)
matter = matters_svc.get_matter(db, invoice.matter_id)
matters_svc.assert_can_read(db, user, matter)
client = parties_svc.get_party(db, invoice.client_party_id)
return {
"invoice": invoice_out(invoice, matter=matter, client=client),
"lines": [invoice_line_out(x) for x in billing.lines_of(db, invoice)],
}
def _billable(db: Session, user: AppUser, invoice_id: uuid.UUID):
invoice = billing.get_invoice(db, invoice_id)
matter = matters_svc.get_matter(db, invoice.matter_id)
billing.assert_can_bill(db, user, matter)
return invoice, matter
@router.post("/invoices/{invoice_id}/approve")
def approve(invoice_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
invoice, matter = _billable(db, user, invoice_id)
billing.approve(db, invoice, user)
audit.record(db, actor_id=user.id, action="invoice.approve", entity_type="matter",
entity_id=matter.id, detail=f"{invoice.gross_minor / 100:.2f}",
ip=client_ip(request))
db.commit()
return invoice_out(invoice, matter=matter)
@router.post("/invoices/{invoice_id}/issue")
def issue(invoice_id: uuid.UUID, body: IssueIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
invoice, matter = _billable(db, user, invoice_id)
billing.issue(db, invoice, user, issued_on=body.issued_on, payment_days=body.payment_days)
audit.record(db, actor_id=user.id, action="invoice.issue", entity_type="matter",
entity_id=matter.id, detail=invoice.number, ip=client_ip(request))
db.commit()
return invoice_out(invoice, matter=matter)
@router.post("/invoices/{invoice_id}/payment")
def payment(invoice_id: uuid.UUID, body: PaymentIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
invoice, matter = _billable(db, user, invoice_id)
billing.register_payment(db, invoice, amount_minor=body.amount_minor, paid_on=body.paid_on)
audit.record(db, actor_id=user.id, action="invoice.payment", entity_type="matter",
entity_id=matter.id,
detail=f"{invoice.number}: {body.amount_minor / 100:.2f}",
ip=client_ip(request))
db.commit()
return invoice_out(invoice, matter=matter)
@router.post("/invoices/{invoice_id}/settle-from-deposit")
def settle_from_deposit(invoice_id: uuid.UUID, request: Request,
db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
invoice, matter = _billable(db, user, invoice_id)
billing.settle_from_deposit(db, invoice, user, matter)
audit.record(db, actor_id=user.id, action="invoice.settle_deposit", entity_type="matter",
entity_id=matter.id, detail=invoice.number, ip=client_ip(request))
db.commit()
return invoice_out(invoice, matter=matter)
@router.post("/invoices/{invoice_id}/credit-note")
def credit_note(invoice_id: uuid.UUID, body: CreditNoteIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
invoice, matter = _billable(db, user, invoice_id)
note = billing.credit_note(db, invoice, user, reason=body.reason)
audit.record(db, actor_id=user.id, action="invoice.credit_note", entity_type="matter",
entity_id=matter.id, detail=f"{invoice.number}: {body.reason[:60]}",
ip=client_ip(request))
db.commit()
return invoice_out(note, matter=matter)
@router.delete("/invoices/{invoice_id}")
def delete_draft(invoice_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
invoice, matter = _billable(db, user, invoice_id)
billing.cancel_draft(db, invoice)
audit.record(db, actor_id=user.id, action="invoice.delete_draft", entity_type="matter",
entity_id=matter.id, ip=client_ip(request))
db.commit()
return {"ok": True}
@router.get("/billing/summary")
def summary(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Firm-wide WIP and debt, over the matters this user may read."""
return billing.firm_summary(db, user)
+66
View File
@@ -0,0 +1,66 @@
"""Conflict of interest — the intake gate.
`POST /conflicts/search` is a dry run that writes nothing, so the intake form can show hits as
the user types a name. `POST /conflicts` records the check; only a recorded, decided check can
open a matter.
"""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..models import AppUser
from ..schemas import ConflictDecisionIn, ConflictSearchIn, conflict_out
from ..services import audit, conflicts
router = APIRouter(prefix="/conflicts", tags=["conflicts"])
@router.post("/search")
def preview(body: ConflictSearchIn, db: Session = Depends(get_db),
_: 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)}
@router.post("")
def run(body: ConflictSearchIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
check = conflicts.run(
db, user, subject=body.subject, adverse_names=body.adverse_names,
lead_id=uuid.UUID(body.lead_id) if body.lead_id else None,
)
audit.record(db, actor_id=user.id, action="conflict.run", entity_type="conflict_check",
entity_id=check.id,
detail=f"{check.subject} — {check.hit_count} trafień, {check.outcome.value}",
ip=client_ip(request))
db.commit()
return conflict_out(check)
@router.get("")
def recent(db: Session = Depends(get_db), _: AppUser = Depends(get_current_user)):
return [conflict_out(c) for c in 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))
@router.post("/{check_id}/decide")
def decide(check_id: uuid.UUID, body: ConflictDecisionIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
check = conflicts.get(db, check_id)
conflicts.decide(db, check, user, outcome=body.outcome, note=body.note)
audit.record(db, actor_id=user.id, action="conflict.decide", entity_type="conflict_check",
entity_id=check.id, detail=f"{check.subject} → {check.outcome.value}",
ip=client_ip(request))
db.commit()
return conflict_out(check)
+192
View File
@@ -0,0 +1,192 @@
"""Correspondence — the inbox and the chain from a service date to a deadline.
Phase 2's e-Doręczenia and Portal Informacyjny connectors write through
`services/correspondence.record`, the same function these endpoints use, so they inherit the
idempotency and service-date rules instead of re-implementing them.
"""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..enums import NodeRole
from ..models import AppUser
from ..schemas import (
AssignIn,
CorrespondenceIn,
CorrespondenceStatusIn,
DeriveFromCorrespondenceIn,
ServiceDateIn,
correspondence_out,
deadline_out,
)
from ..services import audit, correspondence as corr, matters as matters_svc
router = APIRouter(tags=["correspondence"])
def _matters_by_id(db: Session, items):
ids = {i.matter_id for i in items if i.matter_id}
if not ids:
return {}
return {m.id: m for m in [matters_svc.get_matter(db, i) for i in ids]}
@router.get("/correspondence/inbox")
def inbox(limit: int = Query(200, le=500), db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
"""Unassigned incoming post, plus the items from an authoritative channel that still have
no service date — every one of those is a clock that may already be running.
Both lists are oldest-first, because the longest-ignored item is the most dangerous, and
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)
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),
"limit": limit,
}
@router.post("/correspondence")
def create(body: CorrespondenceIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
matter = None
if body.matter_id:
matter = matters_svc.get_matter(db, uuid.UUID(body.matter_id))
matters_svc.assert_role(db, user, matter, NodeRole.editor)
fields = body.model_dump(
exclude={"channel", "subject", "direction", "legal_service_date", "matter_id",
"external_ref"}
)
item = corr.record(
db, user, channel=body.channel, subject=body.subject, direction=body.direction,
legal_service_date=body.legal_service_date,
matter_id=matter.id if matter else None,
external_ref=body.external_ref, **fields,
)
audit.record(db, actor_id=user.id, action="correspondence.record",
entity_type="correspondence", entity_id=item.id,
detail=f"{item.channel.value}: {item.subject[:60]}", ip=client_ip(request))
db.commit()
return correspondence_out(item, matter=matter)
@router.get("/correspondence/{item_id}")
def get_item(item_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
item = corr.get(db, item_id)
matter = None
if item.matter_id:
matter = matters_svc.get_matter(db, item.matter_id)
matters_svc.assert_can_read(db, user, matter) # 404 if walled off
derived = corr.derived_deadlines(db, item)
return {
"item": correspondence_out(item, matter=matter, derived_count=len(derived)),
"deadlines": [deadline_out(d) for d in derived],
}
@router.post("/correspondence/{item_id}/assign")
def assign(item_id: uuid.UUID, body: AssignIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
item = corr.get(db, item_id)
matter = matters_svc.get_matter(db, uuid.UUID(body.matter_id))
corr.assign(db, item, matter, user)
audit.record(db, actor_id=user.id, action="correspondence.assign",
entity_type="correspondence", entity_id=item.id,
detail=f"→ {matter.reference}", ip=client_ip(request))
db.commit()
return correspondence_out(item, matter=matter)
@router.post("/correspondence/{item_id}/unassign")
def unassign(item_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
item = corr.get(db, item_id)
if item.matter_id:
matters_svc.assert_role(db, user, matters_svc.get_matter(db, item.matter_id),
NodeRole.editor)
corr.unassign(db, item)
audit.record(db, actor_id=user.id, action="correspondence.unassign",
entity_type="correspondence", entity_id=item.id, ip=client_ip(request))
db.commit()
return correspondence_out(item)
@router.put("/correspondence/{item_id}/service-date")
def set_service_date(item_id: uuid.UUID, body: ServiceDateIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Set or correct the legally binding service date. Refused once deadlines depend on it."""
item = corr.get(db, item_id)
if item.matter_id:
matters_svc.assert_role(db, user, matters_svc.get_matter(db, item.matter_id),
NodeRole.editor)
before = item.legal_service_date
corr.set_service_date(db, item, user, body.legal_service_date)
audit.record(db, actor_id=user.id, action="correspondence.service_date",
entity_type="correspondence", entity_id=item.id,
detail=f"{before or '—'} → {item.legal_service_date}", ip=client_ip(request))
db.commit()
return correspondence_out(item)
@router.put("/correspondence/{item_id}/status")
def set_status(item_id: uuid.UUID, body: CorrespondenceStatusIn, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
item = corr.get(db, item_id)
if item.matter_id:
matters_svc.assert_role(db, user, matters_svc.get_matter(db, item.matter_id),
NodeRole.editor)
corr.set_status(db, item, body.status)
db.commit()
return correspondence_out(item)
@router.delete("/correspondence/{item_id}")
def delete_item(item_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
item = corr.get(db, item_id)
if item.matter_id:
matters_svc.assert_role(db, user, matters_svc.get_matter(db, item.matter_id),
NodeRole.editor)
corr.delete(db, item)
audit.record(db, actor_id=user.id, action="correspondence.delete",
entity_type="correspondence", entity_id=item_id, ip=client_ip(request))
db.commit()
return {"ok": True}
@router.post("/correspondence/{item_id}/deadlines")
def derive_deadline(item_id: uuid.UUID, body: DeriveFromCorrespondenceIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Compute a deadline from this item's service date, linked back to it."""
item = corr.get(db, item_id)
row = corr.derive_deadline(
db, user, item, title=body.title, kind=body.kind, source=body.source, days=body.days,
owner_id=uuid.UUID(body.owner_id) if body.owner_id else None,
)
audit.record(db, actor_id=user.id, action="deadline.derive", entity_type="matter",
entity_id=item.matter_id, detail=f"{row.title} — {row.basis}",
ip=client_ip(request))
db.commit()
return deadline_out(row)
@router.get("/matters/{matter_id}/correspondence")
def for_matter(matter_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
matter = matters_svc.get_matter(db, matter_id)
matters_svc.assert_can_read(db, user, matter)
items = corr.for_matter(db, matter)
return [correspondence_out(i, matter=matter,
derived_count=len(corr.derived_deadlines(db, i)))
for i in items]
+61
View File
@@ -0,0 +1,61 @@
"""Pulpit — the first screen: what is due, what needs a second pair of eyes, what I've recorded."""
from __future__ import annotations
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..config import get_settings
from ..db import get_db
from ..deps import get_current_user
from ..models import AppUser
from ..services import nodes as nodes_svc, settings as settings_svc, stats
router = APIRouter(tags=["dashboard"])
config = get_settings()
@router.get("/config")
def client_config(db: Session = Depends(get_db), _: AppUser = Depends(get_current_user)):
"""What the console needs to render itself, fetched once at sign-in.
`practice_mode` is the in-house switch: the same matters, deadlines and conflicts, minus the
parts that only exist when you bill someone."""
mode = settings_svc.get(db, "practice_mode") or "law_firm"
return {
"firm_name": settings_svc.get(db, "firm_name"),
"practice_mode": mode,
"bills_clients": mode != "in_house",
"currency": settings_svc.get(db, "currency"),
}
@router.get("/shell")
def shell(_: AppUser = Depends(get_current_user)):
"""What the launcher shows: the other applications in this firm's shared system.
Stage C is one shell over two applications (PLAN.md §3.4). Sygna knows about Galena because
it stores documents there; anything else a firm runs is its own business, so this is a list
rather than a hard-coded pair. Available to every signed-in user — a launcher only an
administrator can see is not a launcher."""
apps = [{"key": "sygna", "name": "Sygna", "role": "Sprawy, terminy, czas pracy",
"url": None, "current": True}]
if config.galena_console:
apps.append({"key": "galena", "name": "Galena", "role": "Akta spraw i dokumenty",
"url": config.galena_console, "current": False})
return {"apps": apps, "embed": config.galena_embed and bool(config.galena_origin)}
@router.get("/dashboard")
def dashboard(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
return stats.dashboard(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."""
return [
{"action": r.action, "detail": r.detail, "at": r.created_at.isoformat(),
"entity_type": r.entity_type,
"entity_id": str(r.entity_id) if r.entity_id else None}
for r in nodes_svc.recent(db, user)
]
+134
View File
@@ -0,0 +1,134 @@
"""Deadlines (terminy) and court events."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..enums import NodeRole
from ..models import AppUser
from ..schemas import (
CourtEventIn,
DeadlineDeriveIn,
DeadlineIn,
court_event_out,
deadline_out,
)
from ..services import audit, deadlines, matters
router = APIRouter(tags=["deadlines"])
@router.get("/deadlines")
def upcoming(days: int = Query(14, ge=1, le=365), mine: bool = False,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
rows = deadlines.upcoming(db, user, days=days, mine=mine)
return [
{**deadline_out(d), "matter_reference": m.reference, "matter_name": m.name}
for d, m in rows
]
@router.get("/matters/{matter_id}/deadlines")
def for_matter(matter_id: uuid.UUID, include_done: bool = False,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_can_read(db, user, matter)
return [deadline_out(d) for d in deadlines.for_matter(db, matter, include_done=include_done)]
@router.post("/matters/{matter_id}/deadlines")
def create(matter_id: uuid.UUID, body: DeadlineIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
row = deadlines.create(
db, user, matter, title=body.title, kind=body.kind, source=body.source,
due_date=body.due_date, basis=body.basis, notes=body.notes,
owner_id=uuid.UUID(body.owner_id) if body.owner_id else None,
)
audit.record(db, actor_id=user.id, action="deadline.create", entity_type="matter",
entity_id=matter.id, detail=f"{row.title} — {row.due_date.isoformat()}",
ip=client_ip(request))
db.commit()
return deadline_out(row)
@router.post("/matters/{matter_id}/deadlines/derive")
def derive(matter_id: uuid.UUID, body: DeadlineDeriveIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Compute a deadline from a service date, recording how it was reached."""
matter = matters.get_matter(db, matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
row = deadlines.derive(
db, user, matter, title=body.title, kind=body.kind, source=body.source,
service_date=body.service_date, days=body.days,
owner_id=uuid.UUID(body.owner_id) if body.owner_id else None,
)
audit.record(db, actor_id=user.id, action="deadline.derive", entity_type="matter",
entity_id=matter.id, detail=f"{row.title} — {row.basis}",
ip=client_ip(request))
db.commit()
return deadline_out(row)
@router.post("/deadlines/{deadline_id}/confirm")
def confirm(deadline_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
row = deadlines.get_deadline(db, deadline_id)
matter = matters.get_matter(db, row.matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
deadlines.confirm(db, row, user)
audit.record(db, actor_id=user.id, action="deadline.confirm", entity_type="matter",
entity_id=matter.id, detail=row.title, ip=client_ip(request))
db.commit()
return deadline_out(row)
@router.post("/deadlines/{deadline_id}/complete")
def complete(deadline_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
row = deadlines.get_deadline(db, deadline_id)
matter = matters.get_matter(db, row.matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
deadlines.complete(db, row, user)
audit.record(db, actor_id=user.id, action="deadline.complete", entity_type="matter",
entity_id=matter.id, detail=row.title, ip=client_ip(request))
db.commit()
return deadline_out(row)
@router.post("/deadlines/{deadline_id}/reopen")
def reopen(deadline_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
row = deadlines.get_deadline(db, deadline_id)
matter = matters.get_matter(db, row.matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
deadlines.reopen(db, row)
db.commit()
return deadline_out(row)
# ── court events ──────────────────────────────────────────────────────────────
@router.get("/matters/{matter_id}/events")
def events(matter_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_can_read(db, user, matter)
return [court_event_out(e) for e in deadlines.events_for_matter(db, matter)]
@router.post("/matters/{matter_id}/events")
def create_event(matter_id: uuid.UUID, body: CourtEventIn, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
fields = body.model_dump(exclude={"title", "starts_at"})
if fields.get("attending_id"):
fields["attending_id"] = uuid.UUID(fields["attending_id"])
row = deadlines.create_event(db, matter, title=body.title, starts_at=body.starts_at, **fields)
db.commit()
return court_event_out(row)
+54
View File
@@ -0,0 +1,54 @@
"""Court fees and statutory representation costs.
Pure computation, so these endpoints touch no database except to read a matter's value in
dispute. Every response carries the schedule version, the statutes it came from, and a note
telling the reader to verify — the numbers have a shelf life and the UI must not pretend
otherwise.
"""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import get_current_user
from ..errors import ConflictError
from ..models import AppUser
from ..schemas import FeeEstimateIn
from ..services import fees, matters as matters_svc
router = APIRouter(tags=["fees"])
@router.get("/fees/options")
def options(_: AppUser = Depends(get_current_user)):
"""The pickers, their percentages and their legal bases — so the console never hardcodes a
label that the schedule later contradicts."""
return fees.options()
@router.post("/fees/estimate")
def estimate(body: FeeEstimateIn, _: AppUser = Depends(get_current_user)):
return fees.estimate(
body.value_minor, proceeding=body.proceeding, stage=body.stage,
multiplier=body.multiplier, powers_of_attorney=body.powers_of_attorney,
)
@router.get("/matters/{matter_id}/fees")
def for_matter(matter_id: uuid.UUID, proceeding: str = "pozew", stage: str = "i_instancja",
multiplier: int = 1, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
"""The estimate for this matter's value in dispute."""
matter = matters_svc.get_matter(db, matter_id)
matters_svc.assert_can_read(db, user, matter)
if matter.value_in_dispute is None:
raise ConflictError(
"Ta sprawa nie ma podanej wartości przedmiotu sporu — bez niej nie ma od czego "
"liczyć opłaty."
)
value_minor = int(round(float(matter.value_in_dispute) * 100))
return fees.estimate(value_minor, proceeding=proceeding, stage=stage,
multiplier=multiplier)
+13
View File
@@ -0,0 +1,13 @@
"""Liveness."""
from __future__ import annotations
from fastapi import APIRouter
from .. import __version__
router = APIRouter(tags=["health"])
@router.get("/health")
def health() -> dict:
return {"status": "ok", "service": "sygna", "version": __version__}
+66
View File
@@ -0,0 +1,66 @@
"""Intake — enquiries (leads) and their conflict checks."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
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 ..services import audit, leads
router = APIRouter(prefix="/leads", tags=["intake"])
@router.get("")
def list_leads(stage: LeadStage | None = None, db: Session = Depends(get_db),
_: AppUser = Depends(get_current_user)):
return [lead_out(row) for row in leads.listing(db, stage=stage)]
@router.post("")
def create_lead(body: LeadIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
fields = body.model_dump(exclude={"name"})
if fields.get("owner_id"):
fields["owner_id"] = uuid.UUID(fields["owner_id"])
row = leads.create(db, user, name=body.name, **fields)
audit.record(db, actor_id=user.id, action="lead.create", entity_type="lead",
entity_id=row.id, detail=row.name, ip=client_ip(request))
db.commit()
return lead_out(row)
@router.get("/{lead_id}")
def get_lead(lead_id: uuid.UUID, db: Session = Depends(get_db),
_: 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)]}
@router.patch("/{lead_id}")
def update_lead(lead_id: uuid.UUID, body: LeadIn, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
row = leads.get_lead(db, lead_id)
fields = body.model_dump()
if fields.get("owner_id"):
fields["owner_id"] = uuid.UUID(fields["owner_id"])
leads.update(db, row, **fields)
db.commit()
return lead_out(row)
@router.post("/{lead_id}/lost")
def mark_lost(lead_id: uuid.UUID, body: LeadLostIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
row = leads.get_lead(db, lead_id)
leads.mark_lost(db, row, body.reason)
audit.record(db, actor_id=user.id, action="lead.lost", entity_type="lead",
entity_id=row.id, detail=row.lost_reason, ip=client_ip(request))
db.commit()
return lead_out(row)
+196
View File
@@ -0,0 +1,196 @@
"""Matters (sprawy) — the centre of the application."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, extract_token, get_current_user
from ..enums import MatterStatus, NodeRole
from ..integrations import galena
from ..models import AppUser
from ..schemas import (
MatterOpenIn,
MatterPartyIn,
MatterPatch,
WallIn,
matter_out,
matter_party_out,
wall_out,
)
from ..services import audit, leads as leads_svc, matters, parties as parties_svc, timelog
router = APIRouter(prefix="/matters", tags=["matters"])
def _uuid(value: str | None) -> uuid.UUID | None:
return uuid.UUID(value) if value else None
@router.get("")
def list_matters(q: str = "", status: MatterStatus | None = None, mine: bool = False,
limit: int = Query(200, le=500), db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
found = matters.list_matters(db, user, q=q, status=status, mine=mine, limit=limit)
clients = parties_svc.by_ids(db, [m.client_party_id for m in found])
return [matter_out(m, client=clients.get(m.client_party_id)) for m in found]
@router.post("")
def open_matter(body: MatterOpenIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
"""Open a matter from a decided conflict check. The acting user's token is forwarded to
Galena so the case file is created under their own authority, not the server's."""
fields = body.model_dump(
exclude={"name", "client_party_id", "parent_node_id", "conflict_check_id", "lead_id"}
)
for key in ("responsible_lawyer_id", "originating_lawyer_id"):
if fields.get(key):
fields[key] = uuid.UUID(fields[key])
matter, warning = matters.open_matter(
db, user,
name=body.name,
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),
token=extract_token(request),
**fields,
)
if body.lead_id:
leads_svc.mark_won(db, leads_svc.get_lead(db, uuid.UUID(body.lead_id)), matter.id)
audit.record(db, actor_id=user.id, action="matter.open", entity_type="matter",
entity_id=matter.id, detail=f"{matter.reference} {matter.name}",
ip=client_ip(request))
if warning:
audit.record(db, actor_id=user.id, action="matter.casefile_failed",
entity_type="matter", entity_id=matter.id, detail=warning,
result="fail", ip=client_ip(request))
db.commit()
client = parties_svc.get_party(db, matter.client_party_id)
body_out = matter_out(matter, client=client,
case_file_url=galena.case_file_url(matter.document_node_id))
body_out["case_file_warning"] = warning
return body_out
@router.get("/{matter_id}")
def get_matter(matter_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
role = matters.assert_can_read(db, user, matter)
client = parties_svc.get_party(db, matter.client_party_id)
node = matters.node_of(db, matter)
from ..services import nodes as nodes_svc # local: breadcrumb is a tree concern
crumbs = [{"id": str(n.id), "name": n.name, "kind": n.kind.value}
for n in nodes_svc.breadcrumb(db, node)]
return {
"matter": matter_out(matter, client=client, role=role.value,
case_file_url=galena.case_file_url(matter.document_node_id)),
"parties": [matter_party_out(mp, party)
for mp, party in matters.matter_parties(db, matter)],
"breadcrumb": crumbs,
"totals": timelog.matter_totals(db, matter),
"galena_enabled": galena.enabled(),
# Stage C: when both apps sit under one parent domain and Galena has been prepared to
# be framed, the case file renders inside this screen instead of behind a link.
"galena_embed": galena.embed_enabled(),
}
@router.patch("/{matter_id}")
def update_matter(matter_id: uuid.UUID, body: MatterPatch, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
fields = body.model_dump()
for key in ("responsible_lawyer_id", "originating_lawyer_id", "rate_card_id"):
if fields.get(key):
fields[key] = uuid.UUID(fields[key])
matters.update_matter(db, matter, **fields)
audit.record(db, actor_id=user.id, action="matter.update", entity_type="matter",
entity_id=matter.id, detail=matter.reference, ip=client_ip(request))
db.commit()
client = parties_svc.get_party(db, matter.client_party_id)
return matter_out(matter, client=client,
case_file_url=galena.case_file_url(matter.document_node_id))
@router.post("/{matter_id}/case-file")
def create_case_file(matter_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
"""Retry the Galena case file for a matter that has none."""
matter = matters.get_matter(db, matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
warning = matters.attach_case_file(db, matter, extract_token(request))
audit.record(db, actor_id=user.id, action="matter.casefile", entity_type="matter",
entity_id=matter.id, detail=warning or "ok",
result="fail" if warning else "ok", ip=client_ip(request))
db.commit()
return {"document_node_id": str(matter.document_node_id) if matter.document_node_id else None,
"case_file_url": galena.case_file_url(matter.document_node_id),
"warning": warning}
# ── parties on a matter ───────────────────────────────────────────────────────
@router.post("/{matter_id}/parties")
def add_party(matter_id: uuid.UUID, body: MatterPartyIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
party = parties_svc.get_party(db, uuid.UUID(body.party_id))
row = matters.add_party(db, matter, party, body.role, body.note)
audit.record(db, actor_id=user.id, action="matter.party_add", entity_type="matter",
entity_id=matter.id, detail=f"{party.name} ({body.role.value})",
ip=client_ip(request))
db.commit()
return matter_party_out(row, party)
@router.delete("/{matter_id}/parties/{matter_party_id}")
def remove_party(matter_id: uuid.UUID, matter_party_id: uuid.UUID, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
matters.remove_party(db, matter, matter_party_id)
audit.record(db, actor_id=user.id, action="matter.party_remove", entity_type="matter",
entity_id=matter.id, detail=str(matter_party_id), ip=client_ip(request))
db.commit()
return {"ok": True}
# ── ethical walls ─────────────────────────────────────────────────────────────
@router.get("/{matter_id}/walls")
def list_walls(matter_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_wall_admin(db, user, matter)
return [wall_out(w, target) for w, target in matters.walls(db, matter)]
@router.post("/{matter_id}/walls")
def set_wall(matter_id: uuid.UUID, body: WallIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_wall_admin(db, user, matter)
row = matters.set_wall(db, matter, user, user_id=uuid.UUID(body.user_id),
mode=body.mode, reason=body.reason)
audit.record(db, actor_id=user.id, action="matter.wall_set", entity_type="matter",
entity_id=matter.id, detail=f"{body.user_id} → {body.mode.value}",
ip=client_ip(request))
db.commit()
return {"ok": True, "id": str(row.id)}
@router.delete("/{matter_id}/walls/{user_id}")
def clear_wall(matter_id: uuid.UUID, user_id: uuid.UUID, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_wall_admin(db, user, matter)
removed = matters.clear_wall(db, matter, user_id)
if removed:
audit.record(db, actor_id=user.id, action="matter.wall_clear", entity_type="matter",
entity_id=matter.id, detail=str(user_id), ip=client_ip(request))
db.commit()
return {"ok": removed}
+130
View File
@@ -0,0 +1,130 @@
"""The organizational tree: firm → departments/teams → matters."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..enums import NodeKind, NodeRole
from ..errors import ConflictError
from ..models import AppUser, Node
from ..schemas import NodeCreate, NodeMove, NodeRename, node_out
from ..services import audit, authz, matters as matters_svc, nodes
router = APIRouter(tags=["nodes"])
def _annotate(db: Session, user: AppUser, node: Node, favs: set) -> dict:
return node_out(node, access=authz.access_state(db, user, node), favorite=node.id in favs)
@router.get("/tree/home")
def home(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
personal = nodes.personal_workspace(db, user)
db.commit()
favs = nodes.favorite_ids(db, user)
workspaces = [_annotate(db, user, w, favs) for w in nodes.accessible_workspaces(db, user)]
return {"personal_id": str(personal.id), "personal": _annotate(db, user, personal, favs),
"workspaces": workspaces}
@router.get("/tree/containers")
def containers(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Everywhere the user may open a matter — the parent picker on the intake form."""
found = nodes.containers(db)
readable = authz.readable_node_ids(db, user, found)
out = []
for node in found:
if node.id not in readable:
continue
role = authz.effective_role(db, user, node)
if NodeRole.rank(role) >= NodeRole.rank(NodeRole.editor):
out.append(node_out(node))
return out
@router.get("/nodes/{node_id}")
def get_node(node_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_can_read(db, user, node)
favs = nodes.favorite_ids(db, user)
children = [_annotate(db, user, c, favs) for c in nodes.children(db, node)
if authz.effective_role(db, user, c) is not None]
crumbs = [{"id": str(n.id), "name": n.name, "kind": n.kind.value}
for n in nodes.breadcrumb(db, node)]
matter = matters_svc.get_by_node(db, node.id)
return {"node": _annotate(db, user, node, favs), "children": children,
"breadcrumb": crumbs, "matter_id": str(matter.id) if matter else None}
@router.post("/nodes")
def create_node(body: NodeCreate, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
if body.kind == NodeKind.matter:
raise ConflictError(
"Sprawy zakłada się przez sprawdzenie konfliktu interesów (POST /matters)."
)
parent = nodes.get_node(db, uuid.UUID(body.parent_id)) if body.parent_id else None
if parent is not None:
authz.assert_role(db, user, parent, NodeRole.manager)
elif not user.is_admin:
raise ConflictError("Nową kancelarię (workspace) może utworzyć administrator.")
node = nodes.create_node(db, user, parent=parent, kind=body.kind, name=body.name)
audit.record(db, actor_id=user.id, action="node.create", entity_type="node",
entity_id=node.id, detail=node.path, ip=client_ip(request))
db.commit()
return node_out(node)
@router.patch("/nodes/{node_id}")
def rename_node(node_id: uuid.UUID, body: NodeRename, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
nodes.rename(db, node, body.name)
audit.record(db, actor_id=user.id, action="node.rename", entity_type="node",
entity_id=node.id, detail=node.path, ip=client_ip(request))
db.commit()
return node_out(node)
@router.post("/nodes/{node_id}/move")
def move_node(node_id: uuid.UUID, body: NodeMove, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
parent = nodes.get_node(db, uuid.UUID(body.parent_id)) if body.parent_id else None
if parent is not None:
authz.assert_role(db, user, parent, NodeRole.manager)
nodes.move(db, node, parent)
audit.record(db, actor_id=user.id, action="node.move", entity_type="node",
entity_id=node.id, detail=node.path, ip=client_ip(request))
db.commit()
return node_out(node)
@router.delete("/nodes/{node_id}")
def delete_node(node_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
path = node.path
nodes.delete(db, node)
audit.record(db, actor_id=user.id, action="node.delete", entity_type="node",
entity_id=node_id, detail=path, ip=client_ip(request))
db.commit()
return {"ok": True}
@router.post("/nodes/{node_id}/favorite")
def toggle_favorite(node_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_can_read(db, user, node)
state = nodes.toggle_favorite(db, user, node)
db.commit()
return {"favorite": state}
+74
View File
@@ -0,0 +1,74 @@
"""Notifications and the reminder run."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user, require_admin
from ..models import AppUser
from ..schemas import PrefsIn, notification_out
from ..services import audit, notify, reminders
router = APIRouter(tags=["notifications"])
@router.get("/notifications")
def listing(unread_only: bool = False, limit: int = Query(50, le=200),
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
rows = notify.listing(db, user.id, limit=limit, unread_only=unread_only)
return {"unread": notify.unread_count(db, user.id),
"items": [notification_out(n) for n in rows]}
@router.get("/notifications/unread")
def unread(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Polled by the console's bell — deliberately tiny."""
return {"unread": notify.unread_count(db, user.id)}
@router.post("/notifications/{notification_id}/read")
def read_one(notification_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
ok = notify.mark_read(db, user.id, notification_id)
db.commit()
return {"ok": ok, "unread": notify.unread_count(db, user.id)}
@router.post("/notifications/read-all")
def read_all(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
count = notify.mark_all_read(db, user.id)
db.commit()
return {"ok": True, "marked": count}
@router.get("/notifications/prefs")
def get_prefs(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
row = notify.prefs_for(db, user.id)
db.commit()
return {"inapp": row.inapp, "webpush": row.webpush, "email": row.email}
@router.put("/notifications/prefs")
def put_prefs(body: PrefsIn, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
row = notify.set_prefs(db, user.id, **body.model_dump())
db.commit()
return {"inapp": row.inapp, "webpush": row.webpush, "email": row.email}
@router.post("/admin/reminders/run")
def run_reminders(request: Request, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
"""Trigger a reminder pass by hand.
Safe at any time: every reminder is deduplicated by a database constraint, so this cannot
double-notify anyone — which is exactly why it is useful for checking the engine works
without waiting for the scheduler."""
counts = reminders.run(db)
audit.record(db, actor_id=admin.id, action="reminders.run", entity_type="app_setting",
detail=str(counts), ip=client_ip(request))
db.commit()
return counts
+83
View File
@@ -0,0 +1,83 @@
"""Parties — clients, opponents, courts, experts.
Party records are firm-wide by design: the conflict engine cannot work on a partitioned view of
who the firm knows. What a party record does NOT expose is which matters it appears in — that
comes from the matter endpoints, which are permission-filtered.
"""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..models import AppUser
from ..schemas import AliasIn, PartyIn, PartyLinkIn, party_out
from ..services import audit, parties
router = APIRouter(prefix="/parties", tags=["parties"])
@router.get("")
def list_parties(q: str = "", limit: int = Query(100, le=500),
db: Session = Depends(get_db), _: AppUser = Depends(get_current_user)):
return [party_out(p) for p in parties.list_parties(db, q=q, limit=limit)]
@router.post("")
def create_party(body: PartyIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
fields = body.model_dump(exclude={"kind", "name"})
party = parties.create_party(db, user, kind=body.kind, name=body.name, **fields)
audit.record(db, actor_id=user.id, action="party.create", entity_type="party",
entity_id=party.id, detail=party.name, ip=client_ip(request))
db.commit()
return party_out(party)
@router.get("/{party_id}")
def get_party(party_id: uuid.UUID, db: Session = Depends(get_db),
_: AppUser = Depends(get_current_user)):
party = parties.get_party(db, party_id)
return {
"party": party_out(party),
"aliases": [{"id": str(a.id), "alias": a.alias}
for a in parties.aliases_for(db, party)],
"links": [{"id": str(link.id), "to_party_id": str(other.id),
"to_party_name": other.name, "relation": link.relation.value,
"note": link.note}
for link, other in parties.links_for(db, party)],
}
@router.patch("/{party_id}")
def update_party(party_id: uuid.UUID, body: PartyIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
party = parties.get_party(db, party_id)
parties.update_party(db, party, **body.model_dump())
audit.record(db, actor_id=user.id, action="party.update", entity_type="party",
entity_id=party.id, detail=party.name, ip=client_ip(request))
db.commit()
return party_out(party)
@router.post("/{party_id}/aliases")
def add_alias(party_id: uuid.UUID, body: AliasIn, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
party = parties.get_party(db, party_id)
alias = parties.add_alias(db, party, body.alias)
db.commit()
return {"id": str(alias.id), "alias": alias.alias}
@router.post("/{party_id}/links")
def add_link(party_id: uuid.UUID, body: PartyLinkIn, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
party = parties.get_party(db, party_id)
other = parties.get_party(db, uuid.UUID(body.to_party_id))
link = parties.link(db, party, other, body.relation, body.note)
db.commit()
return {"id": str(link.id), "to_party_id": str(other.id), "to_party_name": other.name,
"relation": link.relation.value, "note": link.note}
+52
View File
@@ -0,0 +1,52 @@
"""Access grants on a node. `services/authz` owns every read and write here."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..enums import NodeRole
from ..models import AppUser
from ..schemas import GrantIn
from ..services import audit, authz, nodes
router = APIRouter(prefix="/nodes/{node_id}/access", tags=["permissions"])
@router.get("")
def list_access(node_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
return authz.list_grants_for_display(db, node)
@router.post("")
def grant(node_id: uuid.UUID, body: GrantIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
_grant, target = authz.upsert_user_grant(
db, node, uuid.UUID(body.user_id), body.role, user.id
)
audit.record(db, actor_id=user.id, action="access.grant", entity_type="node",
entity_id=node.id, detail=f"{target.email} → {body.role.value}",
ip=client_ip(request))
db.commit()
return {"ok": True}
@router.delete("/{target_id}")
def revoke(node_id: uuid.UUID, target_id: uuid.UUID, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
removed = authz.remove_user_grant(db, node.id, target_id)
if removed:
audit.record(db, actor_id=user.id, action="access.revoke", entity_type="node",
entity_id=node.id, detail=str(target_id), ip=client_ip(request))
db.commit()
return {"ok": removed}
+154
View File
@@ -0,0 +1,154 @@
"""Rate cards, lawyer profiles, and rate resolution.
Managing cards is an administrator's job — a rate is a commercial term, not a case detail.
Reading the resolved rate is open to anyone who can read the matter, because the person
recording time needs to see what it will be billed at before they save it.
"""
from __future__ import annotations
import datetime as dt
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user, require_admin
from ..models import AppUser
from ..schemas import (
LawyerProfileIn,
RateCardIn,
RateCardPatch,
RateEntryIn,
lawyer_profile_out,
rate_card_out,
rate_entry_out,
)
from ..services import audit, auth as auth_svc, matters as matters_svc, parties as parties_svc
from ..services import rates
router = APIRouter(tags=["rates"])
# ── cards ─────────────────────────────────────────────────────────────────────
@router.get("/rate-cards")
def list_cards(db: Session = Depends(get_db), _: AppUser = Depends(get_current_user)):
cards = rates.list_cards(db)
clients = parties_svc.by_ids(db, [c.client_party_id for c in cards if c.client_party_id])
return [rate_card_out(c, client=clients.get(c.client_party_id),
entry_count=len(rates.entries(db, c)))
for c in cards]
@router.post("/rate-cards")
def create_card(body: RateCardIn, request: Request, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
card = rates.create_card(
db, admin, name=body.name, valid_from=body.valid_from, valid_to=body.valid_to,
client_party_id=uuid.UUID(body.client_party_id) if body.client_party_id else None,
is_default=body.is_default, currency=body.currency, note=body.note,
)
audit.record(db, actor_id=admin.id, action="rate_card.create", entity_type="rate_card",
entity_id=card.id, detail=card.name, ip=client_ip(request))
db.commit()
return rate_card_out(card)
@router.get("/rate-cards/{card_id}")
def get_card(card_id: uuid.UUID, db: Session = Depends(get_db),
_: AppUser = Depends(get_current_user)):
card = rates.get_card(db, card_id)
rows = rates.entries(db, card)
users = {u.id: u for u in auth_svc.list_users(db)}
client = (parties_svc.by_ids(db, [card.client_party_id]).get(card.client_party_id)
if card.client_party_id else None)
return {
"card": rate_card_out(card, client=client, entry_count=len(rows)),
"entries": [rate_entry_out(e, user=users.get(e.user_id)) for e in rows],
}
@router.patch("/rate-cards/{card_id}")
def patch_card(card_id: uuid.UUID, body: RateCardPatch, request: Request,
db: Session = Depends(get_db), admin: AppUser = Depends(require_admin)):
card = rates.get_card(db, card_id)
rates.update_card(db, card, **body.model_dump())
audit.record(db, actor_id=admin.id, action="rate_card.update", entity_type="rate_card",
entity_id=card.id, detail=card.name, ip=client_ip(request))
db.commit()
return rate_card_out(card)
@router.delete("/rate-cards/{card_id}")
def delete_card(card_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
card = rates.get_card(db, card_id)
name = card.name
rates.delete_card(db, card)
audit.record(db, actor_id=admin.id, action="rate_card.delete", entity_type="rate_card",
entity_id=card_id, detail=name, ip=client_ip(request))
db.commit()
return {"ok": True}
@router.post("/rate-cards/{card_id}/entries")
def set_entry(card_id: uuid.UUID, body: RateEntryIn, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
card = rates.get_card(db, card_id)
row = rates.set_entry(
db, card, rate_minor=body.rate_minor,
user_id=uuid.UUID(body.user_id) if body.user_id else None,
seniority=body.seniority, note=body.note,
)
db.commit()
return rate_entry_out(row, user=auth_svc.get_user(db, row.user_id) if row.user_id else None)
@router.delete("/rate-cards/{card_id}/entries/{entry_id}")
def delete_entry(card_id: uuid.UUID, entry_id: uuid.UUID, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
card = rates.get_card(db, card_id)
rates.delete_entry(db, card, entry_id)
db.commit()
return {"ok": True}
# ── profiles ──────────────────────────────────────────────────────────────────
@router.get("/lawyer-profiles")
def list_profiles(db: Session = Depends(get_db), _: AppUser = Depends(get_current_user)):
users = auth_svc.list_users(db)
profs = rates.profiles(db)
return [
(lawyer_profile_out(profs[u.id], user=u) if u.id in profs
else {"user_id": str(u.id), "name": u.full_name, "seniority": None,
"bar_number": None, "bar_chamber": None, "oc_policy_number": None,
"oc_valid_to": None})
for u in users
]
@router.put("/lawyer-profiles/{user_id}")
def put_profile(user_id: uuid.UUID, body: LawyerProfileIn, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
row = rates.upsert_profile(db, user_id, **body.model_dump())
db.commit()
return lawyer_profile_out(row, user=auth_svc.get_user(db, user_id))
# ── resolution ────────────────────────────────────────────────────────────────
@router.get("/matters/{matter_id}/rates")
def matter_rates(matter_id: uuid.UUID, on_date: dt.date | None = None,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""What everyone would be billed at on this matter, and — first — what *I* would be.
The `mine` block is what the time-entry form shows, so nobody records an hour without
seeing the rate and where it came from."""
matter = matters_svc.get_matter(db, matter_id)
matters_svc.assert_can_read(db, user, matter)
on_date = on_date or dt.date.today()
return {
"on_date": on_date.isoformat(),
"currency": matter.currency,
"mine": rates.resolve(db, matter, user.id, on_date).as_dict(),
"everyone": rates.preview(db, matter, on_date),
}
+67
View File
@@ -0,0 +1,67 @@
"""Public-register lookups and writing them back onto a party."""
from __future__ import annotations
import datetime as dt
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..errors import ValidationError
from ..integrations import registers as connector
from ..models import AppUser
from ..schemas import EnrichIn, party_out
from ..services import audit, parties as parties_svc
from ..services import registers as mapping
router = APIRouter(tags=["registers"])
@router.get("/registers/krs/{krs}")
def krs_lookup(krs: str, registry: str = "P", _: AppUser = Depends(get_current_user)):
"""Look up a company. Read-only — nothing is written until the user says so."""
return connector.krs_lookup(krs, registry)
@router.get("/registers/vat/{nip}")
def vat_lookup(nip: str, on_date: dt.date | None = None,
_: AppUser = Depends(get_current_user)):
return connector.vat_lookup(nip, on_date)
@router.post("/parties/{party_id}/enrich")
def enrich(party_id: uuid.UUID, body: EnrichIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Fill this party's blanks from a register. Returns what changed, so the console can say
so rather than silently mutating a record someone is looking at."""
party = parties_svc.get_party(db, party_id)
if body.source == "krs":
number = body.number or party.krs
if not number:
raise ValidationError("Podaj numer KRS.")
data = connector.krs_lookup(number)
else:
number = body.number or party.nip
if not number:
raise ValidationError("Podaj NIP.")
data = connector.vat_lookup(number)
updates = mapping.party_updates(data, party, overwrite=body.overwrite)
if updates:
parties_svc.update_party(db, party, **updates)
audit.record(db, actor_id=user.id, action="party.enrich", entity_type="party",
entity_id=party.id,
detail=f"{data['source']}: {', '.join(sorted(updates))}",
ip=client_ip(request))
db.commit()
return {
"party": party_out(party),
"applied": sorted(updates),
"data": data,
# Officer names come back masked from KRS, so the console tells the user to add them by
# hand rather than pretending the conflict engine now knows about them.
"officers_redacted": bool(data.get("officers_redacted")),
}
+61
View File
@@ -0,0 +1,61 @@
"""Management reports. Read-only, and filtered to the matters the reader may see."""
from __future__ import annotations
import datetime as dt
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import get_current_user
from ..models import AppUser
from ..services import reports
router = APIRouter(prefix="/reports", tags=["reports"])
def _period(date_from: dt.date | None, date_to: dt.date | None) -> tuple[dt.date, dt.date]:
default_from, default_to = reports.default_period()
return date_from or default_from, date_to or default_to
@router.get("")
def overview(date_from: dt.date | None = None, date_to: dt.date | None = None,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
start, end = _period(date_from, date_to)
return reports.overview(db, user, start, end)
@router.get("/realisation")
def realisation(date_from: dt.date | None = None, date_to: dt.date | None = None,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
start, end = _period(date_from, date_to)
return reports.realisation(db, user, start, end)
@router.get("/utilisation")
def utilisation(date_from: dt.date | None = None, date_to: dt.date | None = None,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
start, end = _period(date_from, date_to)
return reports.utilisation(db, user, start, end)
@router.get("/profitability")
def profitability(date_from: dt.date | None = None, date_to: dt.date | None = None,
limit: int = Query(100, le=500), db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
"""Least profitable first — the ones worth a conversation are at the top."""
start, end = _period(date_from, date_to)
return reports.profitability(db, user, start, end, limit=limit)
@router.get("/lock-up")
def lock_up(date_from: dt.date | None = None, date_to: dt.date | None = None,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
start, end = _period(date_from, date_to)
return reports.lock_up(db, user, start, end)
@router.get("/aged-debt")
def aged_debt(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
return reports.aged_debt(db, user)
+91
View File
@@ -0,0 +1,91 @@
"""Time entries (karta czasu pracy)."""
from __future__ import annotations
import datetime as dt
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..enums import NodeRole
from ..models import AppUser
from ..schemas import TimeEntryIn, TimeEntryPatch, time_entry_out
from ..services import audit, auth as auth_svc, matters, timelog
router = APIRouter(tags=["time"])
@router.get("/matters/{matter_id}/time")
def for_matter(matter_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_can_read(db, user, matter)
return {
"entries": [time_entry_out(entry, author=author)
for entry, author in timelog.for_matter(db, matter)],
"totals": timelog.matter_totals(db, matter),
}
@router.post("/matters/{matter_id}/time")
def create(matter_id: uuid.UUID, body: TimeEntryIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
matter = matters.get_matter(db, matter_id)
matters.assert_role(db, user, matter, NodeRole.editor)
minutes = timelog.parse_duration(body.duration)
entry = timelog.create(
db, user, matter, minutes=minutes, narrative=body.narrative,
work_date=body.work_date, billable=body.billable,
activity_code=body.activity_code, rate_minor=body.rate_minor,
for_user_id=uuid.UUID(body.for_user_id) if body.for_user_id else None,
)
audit.record(db, actor_id=user.id, action="time.create", entity_type="matter",
entity_id=matter.id, detail=f"{entry.minutes} min — {entry.narrative[:60]}",
ip=client_ip(request))
db.commit()
return time_entry_out(entry, author=auth_svc.get_user(db, entry.user_id))
@router.patch("/time/{entry_id}")
def update(entry_id: uuid.UUID, body: TimeEntryPatch, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
entry = timelog.get_entry(db, entry_id)
matter = matters.get_matter(db, entry.matter_id)
role = matters.assert_role(db, user, matter, NodeRole.editor)
timelog.assert_can_edit(entry, user, role)
fields = body.model_dump(exclude={"duration"})
if body.duration is not None:
fields["minutes"] = timelog.parse_duration(body.duration)
timelog.update(db, entry, **fields)
db.commit()
return time_entry_out(entry, author=auth_svc.get_user(db, entry.user_id))
@router.delete("/time/{entry_id}")
def delete(entry_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
entry = timelog.get_entry(db, entry_id)
matter = matters.get_matter(db, entry.matter_id)
role = matters.assert_role(db, user, matter, NodeRole.editor)
timelog.assert_can_edit(entry, user, role)
timelog.delete(db, entry)
db.commit()
return {"ok": True}
@router.get("/time/mine")
def my_time(date_from: dt.date | None = None, date_to: dt.date | None = None,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""The personal timesheet. Defaults to the current week (Monday → today)."""
today = dt.date.today()
date_from = date_from or today - dt.timedelta(days=today.weekday())
date_to = date_to or today
rows = timelog.for_user(db, user.id, date_from=date_from, date_to=date_to)
return {
"date_from": date_from.isoformat(),
"date_to": date_to.isoformat(),
"total_minutes": sum(entry.minutes for entry, _ in rows),
"entries": [time_entry_out(entry, author=user, matter=matter) for entry, matter in rows],
}
+58
View File
@@ -0,0 +1,58 @@
"""Users. Listing is available to any signed-in user (you must be able to pick a colleague
as a matter's responsible lawyer); creating and editing is admin-only."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user, require_admin
from ..errors import NotFoundError, ValidationError
from ..models import AppUser
from ..schemas import UserCreate, UserPatch, user_out
from ..services import audit
from ..services import auth as auth_service
router = APIRouter(prefix="/users", tags=["users"])
@router.get("")
def list_users(db: Session = Depends(get_db), _: AppUser = Depends(get_current_user)):
return [user_out(u) for u in auth_service.list_users(db)]
@router.post("")
def create_user(body: UserCreate, request: Request, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
user = auth_service.create_user(db, email=body.email, full_name=body.full_name,
password=body.password, is_admin=body.is_admin)
audit.record(db, actor_id=admin.id, action="user.create", entity_type="user",
entity_id=user.id, detail=user.email, ip=client_ip(request))
db.commit()
return user_out(user)
@router.patch("/{user_id}")
def patch_user(user_id: uuid.UUID, body: UserPatch, request: Request,
db: Session = Depends(get_db), admin: AppUser = Depends(require_admin)):
user = auth_service.get_user(db, user_id)
if user is None:
raise NotFoundError("Nie znaleziono użytkownika.")
if body.full_name is not None:
user.full_name = body.full_name.strip()
if body.is_admin is not None:
user.is_admin = body.is_admin
if body.is_active is not None:
user.is_active = body.is_active
if not body.is_active:
auth_service.revoke_user_sessions(db, user.id)
if body.password:
if len(body.password) < 8:
raise ValidationError("Hasło musi mieć co najmniej 8 znaków.")
auth_service.set_password(db, user, body.password)
audit.record(db, actor_id=admin.id, action="user.update", entity_type="user",
entity_id=user.id, detail=user.email, ip=client_ip(request))
db.commit()
return user_out(user)
+624
View File
@@ -0,0 +1,624 @@
"""Pydantic request models + lightweight output serializers.
Serializers are plain functions returning dicts, following Galena's pattern: response shapes are
read where they are built, and a field never appears in the API by accident because someone
added a column.
"""
from __future__ import annotations
import datetime as dt
import re
from typing import Annotated, Any, Literal
from pydantic import AfterValidator, BaseModel, Field
from .enums import (
ConflictOutcome,
CorrespondenceChannel,
CorrespondenceDirection,
CorrespondenceStatus,
DeadlineKind,
DeadlineSource,
DepositMovementKind,
ExpenseKind,
FeeType,
LeadStage,
MatterStatus,
NodeKind,
NodeRole,
PartyKind,
PartyRelation,
PartyRole,
RiskRating,
Seniority,
WallMode,
)
from .models import (
AppUser,
ConflictCheck,
Correspondence,
CourtEvent,
DepositMovement,
Expense,
Invoice,
InvoiceLine,
Deadline,
EthicalWall,
LawyerProfile,
Lead,
Matter,
MatterParty,
Node,
Notification,
Party,
RateCard,
RateCardEntry,
TimeEntry,
)
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
def _valid_email(v: str) -> str:
if not _EMAIL_RE.match(v or ""):
raise ValueError("Enter a valid email address.")
return v.strip()
Email = Annotated[str, AfterValidator(_valid_email)]
# ── auth / users ──
class LoginIn(BaseModel):
email: Email
password: str
class UserCreate(BaseModel):
email: Email
full_name: str = Field(min_length=1)
password: str = Field(min_length=8)
is_admin: bool = False
class UserPatch(BaseModel):
full_name: str | None = None
is_admin: bool | None = None
is_active: bool | None = None
password: str | None = None
# ── nodes / permissions ──
class NodeCreate(BaseModel):
parent_id: str | None = None
kind: NodeKind
name: str = Field(min_length=1)
class NodeRename(BaseModel):
name: str = Field(min_length=1)
class NodeMove(BaseModel):
parent_id: str | None = None
class GrantIn(BaseModel):
user_id: str
role: NodeRole
# ── parties ──
class PartyIn(BaseModel):
kind: PartyKind = PartyKind.organisation
name: str = Field(min_length=1)
nip: str | None = None
pesel: str | None = None
krs: str | None = None
regon: str | None = None
email: str | None = None
phone: str | None = None
address: str | None = None
edoreczenia_address: str | None = None
is_pep: bool | None = None
risk_rating: RiskRating | None = None
notes: str | None = None
class AliasIn(BaseModel):
alias: str = Field(min_length=1)
class EnrichIn(BaseModel):
source: Literal["krs", "vat"] = "krs"
# Falls back to the number already on the party when omitted.
number: str | None = None
overwrite: bool = False
class PartyLinkIn(BaseModel):
to_party_id: str
relation: PartyRelation
note: str | None = None
# ── conflicts / intake ──
class ConflictSearchIn(BaseModel):
subject: str = Field(min_length=1)
adverse_names: str | None = None
lead_id: str | None = None
class ConflictDecisionIn(BaseModel):
outcome: ConflictOutcome
note: str | None = None
class LeadIn(BaseModel):
name: str = Field(min_length=1)
contact_name: str | None = None
email: str | None = None
phone: str | None = None
source: str | None = None
practice_area: str | None = None
summary: str | None = None
adverse_names: str | None = None
estimated_value_minor: int | None = None
stage: LeadStage | None = None
owner_id: str | None = None
class LeadLostIn(BaseModel):
reason: str | None = None
# ── matters ──
class MatterOpenIn(BaseModel):
name: str = Field(min_length=1)
client_party_id: str
parent_node_id: str
conflict_check_id: str
practice_area: str | None = None
description: str | None = None
fee_type: FeeType | None = None
default_rate_minor: int | None = None
value_in_dispute: float | None = None
court: str | None = None
court_department: str | None = None
case_signature: str | None = None
instance: str | None = None
responsible_lawyer_id: str | None = None
originating_lawyer_id: str | None = None
lead_id: str | None = None
class MatterPatch(BaseModel):
name: str | None = None
description: str | None = None
practice_area: str | None = None
status: MatterStatus | None = None
fee_type: FeeType | None = None
default_rate_minor: int | None = None
rate_card_id: str | None = None
fee_cap_minor: int | None = None
value_in_dispute: float | None = None
court: str | None = None
court_department: str | None = None
case_signature: str | None = None
instance: str | None = None
responsible_lawyer_id: str | None = None
originating_lawyer_id: str | None = None
class MatterPartyIn(BaseModel):
party_id: str
role: PartyRole
note: str | None = None
class WallIn(BaseModel):
user_id: str
mode: WallMode
reason: str | None = None
# ── deadlines ──
class DeadlineIn(BaseModel):
title: str = Field(min_length=1)
kind: DeadlineKind
source: DeadlineSource
due_date: dt.date
basis: str | None = None
owner_id: str | None = None
notes: str | None = None
class DeadlineDeriveIn(BaseModel):
title: str = Field(min_length=1)
kind: DeadlineKind
source: DeadlineSource
service_date: dt.date
days: int = Field(gt=0)
owner_id: str | None = None
class CorrespondenceIn(BaseModel):
channel: CorrespondenceChannel
subject: str = Field(min_length=1)
direction: CorrespondenceDirection = CorrespondenceDirection.incoming
legal_service_date: dt.date | None = None
matter_id: str | None = None
sender: str | None = None
recipient: str | None = None
note: str | None = None
external_ref: str | None = None
document_path: str | None = None
class ServiceDateIn(BaseModel):
legal_service_date: dt.date
class AssignIn(BaseModel):
matter_id: str
class CorrespondenceStatusIn(BaseModel):
status: CorrespondenceStatus
class DeriveFromCorrespondenceIn(BaseModel):
title: str = Field(min_length=1)
kind: DeadlineKind
source: DeadlineSource
days: int = Field(gt=0)
owner_id: str | None = None
class CourtEventIn(BaseModel):
title: str = Field(min_length=1)
starts_at: dt.datetime
court: str | None = None
room: str | None = None
attending_id: str | None = None
is_remote: bool | None = None
notes: str | None = None
# ── time ──
class TimeEntryIn(BaseModel):
# Accepts 90, "90m", "1.5", "1:30", "1h30" — parsed by services/timelog.parse_duration.
duration: str | float | int
narrative: str = Field(min_length=1)
work_date: dt.date | None = None
billable: bool = True
activity_code: str | None = None
rate_minor: int | None = None
for_user_id: str | None = None
class TimeEntryPatch(BaseModel):
duration: str | float | int | None = None
narrative: str | None = None
work_date: dt.date | None = None
billable: bool | None = None
activity_code: str | None = None
rate_minor: int | None = None
write_off_minutes: int | None = None
# ── money ──
class ExpenseIn(BaseModel):
kind: ExpenseKind
description: str = Field(min_length=1)
amount_minor: int = Field(gt=0)
spent_on: dt.date | None = None
billable: bool = True
is_passthrough: bool | None = None
paid_from_deposit: bool = False
supplier: str | None = None
document_ref: str | None = None
class DraftInvoiceIn(BaseModel):
group_time: bool = True
vat_rate: int | None = Field(default=None, ge=0, le=100)
note: str | None = None
class IssueIn(BaseModel):
issued_on: dt.date | None = None
payment_days: int | None = Field(default=None, ge=0, le=365)
class PaymentIn(BaseModel):
amount_minor: int = Field(gt=0)
paid_on: dt.date | None = None
class CreditNoteIn(BaseModel):
reason: str = Field(min_length=1)
class DepositMoveIn(BaseModel):
# Signed: positive is a client payment in, negative a refund out.
amount_minor: int
kind: DepositMovementKind = DepositMovementKind.deposit
description: str | None = None
# ── fees ──
class FeeEstimateIn(BaseModel):
# Value in dispute in grosze — integer minor units everywhere near money (invariant 12).
value_minor: int = Field(gt=0)
proceeding: str = "pozew"
stage: str = "i_instancja"
multiplier: int = Field(default=1, ge=1)
powers_of_attorney: int = Field(default=1, ge=0)
# ── rate cards ──
class RateCardIn(BaseModel):
name: str = Field(min_length=1)
valid_from: dt.date
valid_to: dt.date | None = None
client_party_id: str | None = None
is_default: bool = False
currency: str | None = None
note: str | None = None
class RateCardPatch(BaseModel):
name: str | None = None
valid_from: dt.date | None = None
valid_to: dt.date | None = None
is_default: bool | None = None
note: str | None = None
class RateEntryIn(BaseModel):
rate_minor: int = Field(gt=0)
user_id: str | None = None
seniority: Seniority | None = None
note: str | None = None
class LawyerProfileIn(BaseModel):
seniority: Seniority | None = None
bar_number: str | None = None
bar_chamber: str | None = None
oc_policy_number: str | None = None
oc_valid_to: dt.date | None = None
cost_rate_minor: int | None = Field(default=None, ge=0)
# ── notifications ──
class PrefsIn(BaseModel):
inapp: bool | None = None
webpush: bool | None = None
email: bool | None = None
# ── admin ──
class SettingsIn(BaseModel):
values: dict[str, str]
# ── serializers ────────────────────────────────────────────────────────────────
def _id(value: Any) -> str | None:
return str(value) if value else None
def user_out(u: AppUser) -> dict:
return {"id": str(u.id), "email": u.email, "full_name": u.full_name,
"is_admin": u.is_admin, "is_active": u.is_active}
def node_out(n: Node, *, access: str | None = None, favorite: bool | None = None) -> dict:
d = {"id": str(n.id), "parent_id": _id(n.parent_id), "kind": n.kind.value,
"name": n.name, "slug": n.slug, "path": n.path}
if access is not None:
d["access"] = access
if favorite is not None:
d["favorite"] = favorite
return d
def party_out(p: Party) -> dict:
return {"id": str(p.id), "kind": p.kind.value, "name": p.name, "nip": p.nip,
"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}
def matter_out(m: Matter, *, client: Party | None = None, case_file_url: str | None = None,
role: str | None = None) -> dict:
d = {
"id": str(m.id), "node_id": str(m.node_id),
"document_node_id": _id(m.document_node_id),
"reference": m.reference, "name": m.name, "description": m.description,
"client_party_id": str(m.client_party_id),
"client_name": client.name if client else None,
"practice_area": m.practice_area, "status": m.status.value,
"responsible_lawyer_id": _id(m.responsible_lawyer_id),
"originating_lawyer_id": _id(m.originating_lawyer_id),
"opened_at": m.opened_at.isoformat() if m.opened_at else None,
"closed_at": m.closed_at.isoformat() if m.closed_at else None,
"fee_type": m.fee_type.value, "default_rate_minor": m.default_rate_minor,
"rate_card_id": _id(m.rate_card_id),
"fee_cap_minor": m.fee_cap_minor, "currency": m.currency,
"value_in_dispute": float(m.value_in_dispute) if m.value_in_dispute is not None else None,
"court": m.court, "court_department": m.court_department,
"case_signature": m.case_signature, "instance": m.instance,
"case_file_url": case_file_url,
}
if role is not None:
d["role"] = role
return d
def matter_party_out(mp: MatterParty, party: Party) -> dict:
return {"id": str(mp.id), "party_id": str(party.id), "party_name": party.name,
"party_kind": party.kind.value, "role": mp.role.value,
"is_adverse": mp.is_adverse, "note": mp.note}
def conflict_out(c: ConflictCheck) -> dict:
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,
"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),
"decided_at": c.decided_at.isoformat() if c.decided_at else None,
"created_at": c.created_at.isoformat()}
def lead_out(lead: Lead) -> dict:
return {"id": str(lead.id), "name": lead.name, "contact_name": lead.contact_name,
"email": lead.email, "phone": lead.phone, "source": lead.source,
"practice_area": lead.practice_area, "summary": lead.summary,
"adverse_names": lead.adverse_names,
"estimated_value_minor": lead.estimated_value_minor,
"stage": lead.stage.value, "owner_id": _id(lead.owner_id),
"party_id": _id(lead.party_id), "matter_id": _id(lead.matter_id),
"lost_reason": lead.lost_reason, "created_at": lead.created_at.isoformat()}
def deadline_out(d: Deadline, *, today: dt.date | None = None) -> dict:
today = today or dt.date.today()
return {"id": str(d.id), "matter_id": str(d.matter_id), "title": d.title,
"kind": d.kind.value, "source": d.source.value,
"due_date": d.due_date.isoformat(), "basis": d.basis,
"days_left": (d.due_date - today).days,
"overdue": d.completed_at is None and d.due_date < today,
"owner_id": _id(d.owner_id), "created_by_id": _id(d.created_by_id),
"confirmed_by_id": _id(d.confirmed_by_id),
"confirmed_at": d.confirmed_at.isoformat() if d.confirmed_at else None,
"completed_at": d.completed_at.isoformat() if d.completed_at else None,
"notes": d.notes}
def correspondence_out(c: Correspondence, *, matter: Matter | None = None,
derived_count: int | None = None) -> dict:
d = {
"id": str(c.id), "channel": c.channel.value, "direction": c.direction.value,
"status": c.status.value, "subject": c.subject, "sender": c.sender,
"recipient": c.recipient, "note": c.note,
"legal_service_date": c.legal_service_date.isoformat() if c.legal_service_date else None,
"received_at": c.received_at.isoformat() if c.received_at else None,
"sent_at": c.sent_at.isoformat() if c.sent_at else None,
"external_ref": c.external_ref, "document_path": c.document_path,
"matter_id": _id(c.matter_id),
"matter_reference": matter.reference if matter else None,
"matter_name": matter.name if matter else None,
"created_at": c.created_at.isoformat(),
}
if derived_count is not None:
d["derived_deadlines"] = derived_count
return d
def court_event_out(e: CourtEvent) -> dict:
return {"id": str(e.id), "matter_id": str(e.matter_id), "title": e.title,
"starts_at": e.starts_at.isoformat(), "court": e.court, "room": e.room,
"attending_id": _id(e.attending_id), "is_remote": e.is_remote, "notes": e.notes}
def time_entry_out(t: TimeEntry, *, author: AppUser | None = None,
matter: Matter | None = None) -> dict:
return {"id": str(t.id), "matter_id": str(t.matter_id), "user_id": str(t.user_id),
"author": author.full_name if author else None,
"matter_reference": matter.reference if matter else None,
"matter_name": matter.name if matter else None,
"work_date": t.work_date.isoformat(), "minutes": t.minutes,
"hours": round(t.minutes / 60, 2), "narrative": t.narrative,
"activity_code": t.activity_code, "billable": t.billable,
"rate_minor": t.rate_minor, "write_off_minutes": t.write_off_minutes,
"amount_minor": t.amount_minor, "invoiced": t.invoice_id is not None}
def rate_card_out(c: RateCard, *, client: Party | None = None,
entry_count: int | None = None) -> dict:
d = {"id": str(c.id), "name": c.name, "currency": c.currency,
"client_party_id": _id(c.client_party_id),
"client_name": client.name if client else None,
"scope": "klient" if c.client_party_id else ("kancelaria" if c.is_default else "inny"),
"valid_from": c.valid_from.isoformat(),
"valid_to": c.valid_to.isoformat() if c.valid_to else None,
"is_default": c.is_default, "note": c.note}
if entry_count is not None:
d["entries"] = entry_count
return d
def rate_entry_out(e: RateCardEntry, *, user: AppUser | None = None) -> dict:
return {"id": str(e.id), "rate_card_id": str(e.rate_card_id),
"user_id": _id(e.user_id), "user_name": user.full_name if user else None,
"seniority": e.seniority.value if e.seniority else None,
"scope": "osoba" if e.user_id else ("stopień" if e.seniority else "podstawowa"),
"rate_minor": e.rate_minor, "note": e.note}
def lawyer_profile_out(p: LawyerProfile, *, user: AppUser | None = None) -> dict:
return {"user_id": str(p.user_id), "name": user.full_name if user else None,
"seniority": p.seniority.value, "bar_number": p.bar_number,
"bar_chamber": p.bar_chamber, "oc_policy_number": p.oc_policy_number,
"oc_valid_to": p.oc_valid_to.isoformat() if p.oc_valid_to else None,
"cost_rate_minor": p.cost_rate_minor}
def expense_out(e: Expense) -> dict:
return {"id": str(e.id), "matter_id": str(e.matter_id), "kind": e.kind.value,
"spent_on": e.spent_on.isoformat(), "description": e.description,
"amount_minor": e.amount_minor, "is_passthrough": e.is_passthrough,
"billable": e.billable, "paid_from_deposit": e.paid_from_deposit,
"supplier": e.supplier, "document_ref": e.document_ref,
"invoice_id": _id(e.invoice_id)}
def invoice_line_out(line: InvoiceLine) -> dict:
return {"id": str(line.id), "position": line.position, "description": line.description,
"quantity": round(line.quantity_milli / 1000, 3), "unit": line.unit,
"unit_price_minor": line.unit_price_minor, "net_minor": line.net_minor,
"vat_rate": line.vat_rate, "vat_minor": line.vat_minor,
"gross_minor": line.gross_minor, "is_passthrough": line.is_passthrough}
def invoice_out(i: Invoice, *, matter: Matter | None = None,
client: Party | None = None) -> dict:
return {
"id": str(i.id), "kind": i.kind.value, "status": i.status.value, "number": i.number,
"matter_id": str(i.matter_id), "client_party_id": str(i.client_party_id),
"matter_reference": matter.reference if matter else None,
"matter_name": matter.name if matter else None,
"client_name": client.name if client else None,
"issued_on": i.issued_on.isoformat() if i.issued_on else None,
"sold_on": i.sold_on.isoformat() if i.sold_on else None,
"due_on": i.due_on.isoformat() if i.due_on else None,
"paid_on": i.paid_on.isoformat() if i.paid_on else None,
"currency": i.currency, "net_minor": i.net_minor, "vat_minor": i.vat_minor,
"gross_minor": i.gross_minor, "paid_minor": i.paid_minor,
"outstanding_minor": i.gross_minor - i.paid_minor,
"note": i.note, "corrects_invoice_id": _id(i.corrects_invoice_id),
"ksef_status": i.ksef_status.value, "ksef_number": i.ksef_number,
"approved_by_id": _id(i.approved_by_id),
"created_at": i.created_at.isoformat(),
}
def deposit_movement_out(m: DepositMovement) -> dict:
return {"id": str(m.id), "kind": m.kind.value, "amount_minor": m.amount_minor,
"balance_after_minor": m.balance_after_minor, "description": m.description,
"invoice_id": _id(m.invoice_id), "created_at": m.created_at.isoformat()}
def notification_out(n: Notification) -> dict:
return {"id": str(n.id), "kind": n.kind.value, "title": n.title, "body": n.body,
"link": n.link, "read": n.read_at is not None,
"created_at": n.created_at.isoformat()}
def wall_out(w: EthicalWall, user: AppUser) -> dict:
return {"id": str(w.id), "user_id": str(user.id), "user_name": user.full_name,
"mode": w.mode.value, "reason": w.reason}
+38
View File
@@ -0,0 +1,38 @@
"""Password hashing (Argon2id) and opaque session tokens.
Copied from Galena (see SHARED.md), minus the passphrase KDF — Sygna stores no encrypted
blobs of its own; documents live in Galena, which owns that machinery.
"""
from __future__ import annotations
import hashlib
import secrets
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
# Starting parameters (memory-hard).
_hasher = PasswordHasher(memory_cost=65536, time_cost=3, parallelism=2)
def hash_password(password: str) -> str:
return _hasher.hash(password)
def verify_password(password: str, password_hash: str) -> bool:
try:
return _hasher.verify(password_hash, password)
except VerifyMismatchError:
return False
except Exception: # noqa: BLE001 — malformed hash, etc.
return False
def generate_session_token() -> str:
"""Opaque, high-entropy token handed to the client (only its hash is stored)."""
return secrets.token_urlsafe(48)
def hash_token(token: str) -> str:
"""SHA-256 of the session token. Stored server-side; enables an instant kill-switch."""
return hashlib.sha256(token.encode("utf-8")).hexdigest()
+218
View File
@@ -0,0 +1,218 @@
"""Idempotent seed: bootstrap admin, plus a small demo firm so the console isn't empty.
The demo data is deliberately chosen to exercise the conflict engine: `Nowak Transport sp. z
o.o.` is a client in one matter and the opposing party in another, so the first conflict search
a new user runs returns a real hit rather than an empty screen.
"""
from __future__ import annotations
import datetime as dt
import logging
from sqlalchemy import select
from .config import get_settings
from .db import SessionLocal
from .enums import (
ConflictOutcome,
CorrespondenceChannel,
DeadlineKind,
DeadlineSource,
FeeType,
NodeKind,
NodeRole,
PartyKind,
PartyRelation,
PartyRole,
Seniority,
)
from .models import AppUser, Node
from .security import hash_password
from .services import (
authz,
conflicts,
correspondence,
deadlines,
matters,
nodes,
parties,
rates,
timelog,
)
log = logging.getLogger("sygna.seed")
settings = get_settings()
def _demo(db, admin: AppUser) -> None:
if db.scalar(select(Node).where(Node.path == "/kancelaria")) is not None:
return
firm = nodes.create_node(db, admin, parent=None, kind=NodeKind.workspace, name="Kancelaria")
litigation = nodes.create_node(db, admin, parent=firm, kind=NodeKind.group,
name="Dział procesowy")
nodes.create_node(db, admin, parent=firm, kind=NodeKind.group, name="Dział korporacyjny")
lawyer = db.scalar(select(AppUser).where(AppUser.email == "adwokat@example.com"))
if lawyer is None:
lawyer = AppUser(email="adwokat@example.com", full_name="Anna Wiśniewska",
password_hash=hash_password("adwokat12345"))
db.add(lawyer)
db.flush()
authz.upsert_user_grant(db, litigation, lawyer.id, NodeRole.editor, admin.id)
kowalski = parties.create_party(
db, admin, kind=PartyKind.organisation, name="Kowalski Nieruchomości sp. z o.o.",
nip="5252445997", address="ul. Miodowa 14, 00-246 Warszawa",
)
nowak = parties.create_party(
db, admin, kind=PartyKind.organisation, name="Nowak Transport sp. z o.o.",
nip="7010334567", address="ul. Krakowska 8, 31-062 Kraków",
)
nowak_holding = parties.create_party(
db, admin, kind=PartyKind.organisation, name="Nowak Holding S.A.", nip="7010334568",
)
zielinski = parties.create_party(
db, admin, kind=PartyKind.person, name="Piotr Zieliński",
pesel="85010112345", address="ul. Długa 3, 80-827 Gdańsk",
)
parties.add_alias(db, nowak, "Nowak Transport")
parties.link(db, nowak_holding, nowak, PartyRelation.parent_company,
"100% udziałów")
db.flush()
# Rate cards. The firm card prices by grade; the client card is the discount agreed with
# Kowalski to win the relationship. Matter 1 resolves through them; matter 2 carries a flat
# override typed on the matter, so the demo shows both halves of the hierarchy.
rates.upsert_profile(db, admin.id, seniority=Seniority.partner)
rates.upsert_profile(db, lawyer.id, seniority=Seniority.senior_associate)
house = rates.create_card(db, admin, name="Cennik kancelarii 2026",
valid_from=dt.date(2026, 1, 1), is_default=True)
rates.set_entry(db, house, seniority=Seniority.partner, rate_minor=65000)
rates.set_entry(db, house, seniority=Seniority.senior_associate, rate_minor=45000)
rates.set_entry(db, house, seniority=Seniority.associate, rate_minor=32000)
rates.set_entry(db, house, rate_minor=28000, note="Stawka podstawowa cennika")
kowalski_card = rates.create_card(
db, admin, name="Kowalski — stawki umowne", valid_from=dt.date(2026, 3, 1),
client_party_id=kowalski.id, note="Rabat ustalony przy pozyskaniu klienta.",
)
rates.set_entry(db, kowalski_card, seniority=Seniority.partner, rate_minor=52000)
rates.set_entry(db, kowalski_card, rate_minor=38000)
db.flush()
# Matter 1 — Nowak Transport is our client.
check1 = conflicts.run(db, admin, subject=nowak.name, adverse_names=zielinski.name)
matter1, _ = matters.open_matter(
db, admin, name="Windykacja należności — przewóz międzynarodowy",
client_party_id=nowak.id, parent_node_id=litigation.id,
conflict_check_id=check1.id, practice_area="Postępowanie cywilne",
fee_type=FeeType.hourly,
court="Sąd Okręgowy w Krakowie", court_department="IX Wydział Gospodarczy",
case_signature="IX GC 412/26", value_in_dispute=185000,
responsible_lawyer_id=lawyer.id,
)
matters.add_party(db, matter1, zielinski, PartyRole.opponent)
db.flush()
# Matter 2 — Kowalski is the client and Nowak Transport is on the other side. Running a
# conflict check on "Nowak" now returns a real client_conflict hit.
check2 = conflicts.run(db, admin, subject=kowalski.name, adverse_names=nowak.name)
if check2.outcome == ConflictOutcome.pending:
conflicts.decide(db, check2, admin, outcome=ConflictOutcome.waived,
note="Zgoda obu klientów na piśmie z 2026-07-14; wdrożono chiński mur.")
matter2, _ = matters.open_matter(
db, admin, name="Spór o roboty budowlane — hala magazynowa",
client_party_id=kowalski.id, parent_node_id=litigation.id,
conflict_check_id=check2.id, practice_area="Prawo budowlane",
fee_type=FeeType.hourly, default_rate_minor=52000,
court="Sąd Okręgowy w Warszawie", case_signature="XVI GC 88/26",
value_in_dispute=1240000, responsible_lawyer_id=admin.id,
)
matters.add_party(db, matter2, nowak, PartyRole.opponent)
db.flush()
today = dt.date.today()
# The chain the product turns on: a court letter arrives, someone establishes the legally
# binding service date, and the deadline is computed FROM that record — so the deadline can
# always be traced back to the document its date came from.
served = correspondence.record(
db, admin, channel=CorrespondenceChannel.court_portal,
subject="Sprzeciw od nakazu zapłaty — doręczenie przez Portal Informacyjny",
sender="Sąd Okręgowy w Krakowie, IX Wydział Gospodarczy",
legal_service_date=today - dt.timedelta(days=3),
matter_id=matter1.id, external_ref="PI-2026-IXGC-412-0007",
document_path="pisma/2026-sprzeciw.pdf",
)
correspondence.derive_deadline(
db, admin, served, title="Odpowiedź na sprzeciw",
kind=DeadlineKind.procedural, source=DeadlineSource.court, days=14,
owner_id=lawyer.id,
)
# One item waiting in the inbox, and one where nobody has established the service date yet —
# the second is the more dangerous of the two, so the pulpit counts it separately.
correspondence.record(
db, admin, channel=CorrespondenceChannel.edoreczenia,
subject="Wezwanie do uzupełnienia braków formalnych",
sender="Sąd Rejonowy dla Warszawy-Śródmieścia",
legal_service_date=today - dt.timedelta(days=1),
external_ref="EPO-2026-08-0001931",
)
correspondence.record(
db, admin, channel=CorrespondenceChannel.edoreczenia,
subject="Zawiadomienie o terminie rozprawy",
sender="Sąd Okręgowy w Warszawie",
external_ref="EPO-2026-08-0002044",
note="Do ustalenia data doręczenia — sprawdzić EPO w skrzynce.",
)
deadlines.create(db, admin, matter2, title="Termin przedawnienia roszczenia głównego",
kind=DeadlineKind.limitation, source=DeadlineSource.statute,
due_date=today + dt.timedelta(days=45),
basis="art. 118 k.c. — 3 lata od wymagalności 2023-09-30")
deadlines.create_event(
db, matter1, title="Rozprawa",
starts_at=dt.datetime.combine(today + dt.timedelta(days=21), dt.time(10, 30)),
court="Sąd Okręgowy w Krakowie", room="sala 214", attending_id=lawyer.id,
)
timelog.create(db, lawyer, matter1, minutes=95,
narrative="Analiza akt sprawy i dokumentów przewozowych CMR.",
work_date=today - dt.timedelta(days=2))
timelog.create(db, lawyer, matter1, minutes=40,
narrative="Telekonferencja z klientem — ustalenie stanowiska procesowego.",
work_date=today - dt.timedelta(days=1))
timelog.create(db, admin, matter2, minutes=150,
narrative="Sporządzenie projektu pozwu wraz z wnioskami dowodowymi.",
work_date=today)
log.info("Seeded demo firm at /kancelaria (2 matters, 4 parties, 1 real conflict)")
def run() -> None:
db = SessionLocal()
try:
admin = db.scalar(select(AppUser).where(AppUser.email == settings.bootstrap_admin_email))
if admin is None:
admin = AppUser(
email=settings.bootstrap_admin_email,
full_name="Administrator",
password_hash=hash_password(settings.bootstrap_admin_password),
is_admin=True,
)
db.add(admin)
db.commit()
log.info("Created bootstrap admin %s", admin.email)
if settings.seed_demo:
_demo(db, admin)
nodes.personal_workspace(db, admin)
db.commit()
finally:
db.close()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
run()
+1
View File
@@ -0,0 +1 @@
"""Domain services. Routers call these; services own all SQL and all domain rules."""
+37
View File
@@ -0,0 +1,37 @@
"""Append-only audit log writer."""
from __future__ import annotations
import uuid
from sqlalchemy.orm import Session as DbSession
from ..models import AuditLog
def record(
db: DbSession,
*,
actor_id: uuid.UUID | None,
action: str,
entity_type: str,
entity_id: uuid.UUID | None = None,
detail: str | None = None,
ip: str | None = None,
result: str | None = "ok",
request_id: str | None = None,
diff: dict | None = None,
) -> None:
"""Insert one audit row. The `app` DB role has INSERT/SELECT only on audit_log."""
db.add(
AuditLog(
actor_id=actor_id,
action=action,
entity_type=entity_type,
entity_id=entity_id,
detail=detail,
ip=ip,
result=result,
request_id=request_id,
diff=diff,
)
)
+132
View File
@@ -0,0 +1,132 @@
"""Authentication: credential check + server-side sessions (instant kill-switch).
Copied verbatim from Galena — see SHARED.md."""
from __future__ import annotations
import datetime as dt
from sqlalchemy import func, select, update
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..errors import ConflictError
from ..models import AppUser, Session
from ..security import generate_session_token, hash_password, hash_token, verify_password
settings = get_settings()
# A throwaway hash to equalize login timing on the user-missing / inactive / no-password path,
# so latency can't distinguish "unknown email" from "wrong password".
_DUMMY_HASH = hash_password("timing-pad-not-a-real-password")
def find_user_by_email(db: DbSession, email: str) -> AppUser | None:
"""Exact, case-insensitive, wildcard-free lookup backed by uq_app_user_email_lower."""
return db.scalar(select(AppUser).where(func.lower(AppUser.email) == email.lower()))
def list_users(db: DbSession) -> list[AppUser]:
return list(db.scalars(select(AppUser).order_by(AppUser.email)).all())
def get_user(db: DbSession, user_id) -> AppUser | None:
return db.get(AppUser, user_id)
def create_user(db: DbSession, *, email: str, full_name: str, password: str,
is_admin: bool = False) -> AppUser:
if find_user_by_email(db, email):
raise ConflictError("A user with that email already exists.")
user = AppUser(email=email, full_name=full_name,
password_hash=hash_password(password), is_admin=is_admin)
db.add(user)
db.flush()
return user
def authenticate(db: DbSession, email: str, password: str) -> AppUser | None:
"""Return the user on valid credentials, else None. Tracks failures + app-level lockout."""
user = find_user_by_email(db, email)
if user is None or not user.is_active or not user.password_hash:
verify_password(password, _DUMMY_HASH) # equalize timing
return None
now = dt.datetime.now(dt.timezone.utc)
if user.locked_until is not None and user.locked_until > now:
verify_password(password, _DUMMY_HASH)
return None
if not verify_password(password, user.password_hash):
new_count = db.execute(
update(AppUser)
.where(AppUser.id == user.id)
.values(failed_login_count=AppUser.failed_login_count + 1)
.returning(AppUser.failed_login_count)
).scalar_one()
if new_count >= settings.login_max_attempts:
db.execute(
update(AppUser)
.where(AppUser.id == user.id)
.values(
locked_until=now + dt.timedelta(minutes=settings.login_lockout_minutes),
failed_login_count=0,
)
)
return None
if user.failed_login_count or user.locked_until is not None:
db.execute(
update(AppUser).where(AppUser.id == user.id)
.values(failed_login_count=0, locked_until=None)
)
return user
def create_session(db: DbSession, user: AppUser, ip: str | None = None) -> tuple[Session, str]:
"""Create a DB-backed session. Returns (session, raw_token). Only the hash is stored."""
raw_token = generate_session_token()
now = dt.datetime.now(dt.timezone.utc)
session = Session(
user_id=user.id,
token_hash=hash_token(raw_token),
expires_at=now + dt.timedelta(hours=settings.session_ttl_hours),
last_seen_at=now,
created_ip=ip,
)
db.add(session)
db.flush()
return session, raw_token
def resolve_session(db: DbSession, raw_token: str) -> AppUser | None:
"""Validate a token → active user. None if invalid/expired/revoked."""
now = dt.datetime.now(dt.timezone.utc)
session = db.scalar(select(Session).where(Session.token_hash == hash_token(raw_token)))
if session is None or session.revoked_at is not None or session.expires_at <= now:
return None
user = db.get(AppUser, session.user_id)
if user is None or not user.is_active:
return None
if session.last_seen_at is None or now - session.last_seen_at > dt.timedelta(minutes=5):
session.last_seen_at = now
db.commit()
return user
def revoke_session(db: DbSession, raw_token: str) -> None:
session = db.scalar(select(Session).where(Session.token_hash == hash_token(raw_token)))
if session is not None and session.revoked_at is None:
session.revoked_at = dt.datetime.now(dt.timezone.utc)
def revoke_user_sessions(db: DbSession, user_id) -> None:
"""Kill every active session for a user (used on password change → containment)."""
db.execute(
update(Session).where(Session.user_id == user_id, Session.revoked_at.is_(None))
.values(revoked_at=dt.datetime.now(dt.timezone.utc))
)
def set_password(db: DbSession, user: AppUser, password: str) -> None:
user.password_hash = hash_password(password)
revoke_user_sessions(db, user.id)
+284
View File
@@ -0,0 +1,284 @@
"""Effective-role resolution with GitLab-style ancestor-or-self inheritance, plus ethical walls.
Galena's resolver, copied (see SHARED.md), with ONE addition: a matter node is filtered through
`ethical_wall`. A `deny` beats every inherited grant — ownership, manager, and instance-admin
included. That is not an oversight: an information barrier that a partner or an administrator
can walk through is not a barrier. An admin who genuinely needs the file removes the wall, and
that removal is audited.
This module is the single authority for access; routers call assert_* before any read/write.
"""
from __future__ import annotations
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import NodeKind, NodeRole, PrincipalType, WallMode
from ..errors import AuthorizationError, NotFoundError
from ..models import AppUser, EthicalWall, Matter, Node, PermissionGrant
def ancestor_paths(path: str) -> list[str]:
"""All ancestor-or-self paths for '/a/b/c' → ['/a', '/a/b', '/a/b/c']."""
parts = [p for p in path.split("/") if p]
return ["/" + "/".join(parts[: i + 1]) for i in range(len(parts))]
def ancestor_or_self_nodes(db: DbSession, node: Node) -> list[Node]:
paths = ancestor_paths(node.path)
if not paths:
return [node]
return list(db.scalars(select(Node).where(Node.path.in_(paths))).all())
def _wall_mode(db: DbSession, user_id, node: Node) -> WallMode | None:
"""The ethical-wall entry for this user on this node, if the node is a matter."""
if node.kind != NodeKind.matter:
return None
matter_id = db.scalar(select(Matter.id).where(Matter.node_id == node.id))
if matter_id is None:
return None
return db.scalar(
select(EthicalWall.mode).where(
EthicalWall.matter_id == matter_id, EthicalWall.user_id == user_id
)
)
def _base_role(db: DbSession, user: AppUser, node: Node) -> NodeRole | None:
if user.is_admin:
return NodeRole.manager
chain = ancestor_or_self_nodes(db, node)
for n in chain:
if n.personal_owner_id == user.id or n.owner_id == user.id:
return NodeRole.manager
chain_ids = [n.id for n in chain]
grants = db.scalars(
select(PermissionGrant).where(
PermissionGrant.node_id.in_(chain_ids),
PermissionGrant.principal_type == PrincipalType.user,
PermissionGrant.principal_id == user.id,
)
).all()
best: NodeRole | None = None
for g in grants:
if NodeRole.rank(g.role) > NodeRole.rank(best):
best = g.role
return best
def effective_role(db: DbSession, user: AppUser, node: Node) -> NodeRole | None:
"""Highest role the user holds on `node`, or None if no access."""
base = _base_role(db, user, node)
mode = _wall_mode(db, user.id, node)
if mode == WallMode.deny:
return None
if mode == WallMode.allow and base is None:
return NodeRole.viewer
return base
def assert_can_read(db: DbSession, user: AppUser, node: Node) -> NodeRole:
"""Require any access. No access → 404 (the existence of a matter is itself privileged)."""
role = effective_role(db, user, node)
if role is None:
raise NotFoundError("Not found.")
return role
def assert_role(db: DbSession, user: AppUser, node: Node, minimum: NodeRole) -> NodeRole:
"""Require at least `minimum`. None → 404; insufficient → 403."""
role = effective_role(db, user, node)
if role is None:
raise NotFoundError("Not found.")
if NodeRole.rank(role) < NodeRole.rank(minimum):
raise AuthorizationError(f"This needs the '{minimum.value}' role or higher.")
return role
def readable_node_ids(db: DbSession, user: AppUser, nodes: list[Node]) -> set:
"""Filter a batch of nodes to the ones the user can read. Used by list screens so they
don't call effective_role() per row on a page of 200 matters."""
if user.is_admin:
denied = _denied_matter_node_ids(db, user)
return {n.id for n in nodes if n.id not in denied}
grants = db.scalars(
select(PermissionGrant).where(
PermissionGrant.principal_type == PrincipalType.user,
PermissionGrant.principal_id == user.id,
)
).all()
granted_nodes = (
db.scalars(select(Node).where(Node.id.in_([g.node_id for g in grants]))).all()
if grants else []
)
prefixes = [n.path for n in granted_nodes]
owned = db.scalars(
select(Node.path).where(
(Node.owner_id == user.id) | (Node.personal_owner_id == user.id)
)
).all()
prefixes.extend(owned)
denied = _denied_matter_node_ids(db, user)
allowed_extra = _allowed_matter_node_ids(db, user)
out = set()
for n in nodes:
if n.id in denied:
continue
if n.id in allowed_extra or any(n.path == p or n.path.startswith(p + "/") for p in prefixes):
out.add(n.id)
return out
def _denied_matter_node_ids(db: DbSession, user: AppUser) -> set:
return set(
db.scalars(
select(Matter.node_id)
.join(EthicalWall, EthicalWall.matter_id == Matter.id)
.where(EthicalWall.user_id == user.id, EthicalWall.mode == WallMode.deny)
).all()
)
def _allowed_matter_node_ids(db: DbSession, user: AppUser) -> set:
return set(
db.scalars(
select(Matter.node_id)
.join(EthicalWall, EthicalWall.matter_id == Matter.id)
.where(EthicalWall.user_id == user.id, EthicalWall.mode == WallMode.allow)
).all()
)
def users_with_role_at_least(db: DbSession, node: Node, minimum: NodeRole) -> set:
"""User ids holding at least `minimum` on `node` — minus anyone walled off from it."""
chain = ancestor_or_self_nodes(db, node)
ids: set = set()
for n in chain:
if n.owner_id:
ids.add(n.owner_id)
if n.personal_owner_id:
ids.add(n.personal_owner_id)
chain_ids = [n.id for n in chain]
grants = db.scalars(
select(PermissionGrant).where(
PermissionGrant.node_id.in_(chain_ids),
PermissionGrant.principal_type == PrincipalType.user,
)
).all()
for g in grants:
if NodeRole.rank(g.role) >= NodeRole.rank(minimum):
ids.add(g.principal_id)
admins = db.scalars(select(AppUser.id).where(AppUser.is_admin.is_(True))).all()
ids.update(admins)
if node.kind == NodeKind.matter:
matter_id = db.scalar(select(Matter.id).where(Matter.node_id == node.id))
if matter_id is not None:
walled = db.scalars(
select(EthicalWall.user_id).where(
EthicalWall.matter_id == matter_id, EthicalWall.mode == WallMode.deny
)
).all()
ids.difference_update(walled)
return ids
# ── grant CRUD (the single owner of permission-grant reads + mutations) ──────────
def find_user_grant(db: DbSession, node_id, user_id) -> PermissionGrant | None:
return db.scalar(
select(PermissionGrant).where(
PermissionGrant.node_id == node_id,
PermissionGrant.principal_type == PrincipalType.user,
PermissionGrant.principal_id == user_id,
)
)
def upsert_user_grant(db: DbSession, node: Node, target_id, role: NodeRole, created_by):
"""Create or update a user's grant on a node. Raises NotFoundError if the user is unknown."""
target = db.get(AppUser, target_id)
if target is None:
raise NotFoundError("User not found.")
grant = find_user_grant(db, node.id, target.id)
if grant is None:
grant = PermissionGrant(node_id=node.id, principal_type=PrincipalType.user,
principal_id=target.id, role=role, created_by=created_by)
db.add(grant)
else:
grant.role = role
return grant, target
def remove_user_grant(db: DbSession, node_id, target_id) -> bool:
grant = find_user_grant(db, node_id, target_id)
if grant is not None:
db.delete(grant)
return True
return False
def list_grants_for_display(db: DbSession, node: Node) -> dict:
"""Direct + inherited user grants on a node (for the Access dialog), batched into 3 queries."""
chain = ancestor_or_self_nodes(db, node)
node_by_id = {n.id: n for n in chain}
grants = db.scalars(
select(PermissionGrant).where(
PermissionGrant.node_id.in_([n.id for n in chain]),
PermissionGrant.principal_type == PrincipalType.user,
)
).all()
uids = {g.principal_id for g in grants}
if node.owner_id:
uids.add(node.owner_id)
users = ({u.id: u for u in db.scalars(select(AppUser).where(AppUser.id.in_(uids))).all()}
if uids else {})
def _row(g, from_node):
u = users.get(g.principal_id)
return {"user_id": str(g.principal_id), "name": u.full_name if u else "—",
"email": u.email if u else "", "role": g.role.value,
"from": from_node.name if from_node else None,
"from_id": str(from_node.id) if from_node else None}
direct = [_row(g, None) for g in grants if g.node_id == node.id]
inherited = [_row(g, node_by_id.get(g.node_id)) for g in grants if g.node_id != node.id]
owner = users.get(node.owner_id) if node.owner_id else None
return {"direct": direct, "inherited": inherited,
"owner": {"id": str(owner.id), "name": owner.full_name} if owner else None}
def grants_for_user(db: DbSession, user_id) -> list[tuple[Node, NodeRole]]:
"""Every (node, role) granted directly to a user — for the admin per-user access view."""
grants = db.scalars(
select(PermissionGrant).where(
PermissionGrant.principal_type == PrincipalType.user,
PermissionGrant.principal_id == user_id,
)
).all()
if not grants:
return []
nodes_by_id = {n.id: n for n in
db.scalars(select(Node).where(Node.id.in_([g.node_id for g in grants]))).all()}
return [(nodes_by_id[g.node_id], g.role) for g in grants if g.node_id in nodes_by_id]
def access_state(db: DbSession, user: AppUser, node: Node) -> str:
"""Status for the tree badge: 'walled' | 'locked' | 'granted' | 'shared' | 'open'."""
if _wall_mode(db, user.id, node) == WallMode.deny:
return "walled"
role = effective_role(db, user, node)
if role is None:
return "locked"
own_grants = db.scalars(
select(PermissionGrant).where(PermissionGrant.node_id == node.id)
).all()
direct_for_user = any(
g.principal_type == PrincipalType.user and g.principal_id == user.id for g in own_grants
)
if direct_for_user:
return "granted"
others = [g for g in own_grants if not (g.principal_type == PrincipalType.user
and g.principal_id == user.id)]
if others and NodeRole.rank(role) >= NodeRole.rank(NodeRole.manager):
return "shared"
return "open"
+525
View File
@@ -0,0 +1,525 @@
"""Disbursements, invoices and client money.
The shape of the flow, and why:
unbilled time + expenses → draft → approved → issued → paid
↑ │
a partner reads └→ credit note (korekta)
the narratives
- **Drafting is reversible, issuing is not.** A draft can be rebuilt, edited or deleted, and it
releases its time entries when it is. Once issued, the invoice is frozen and the only
correction is a credit note. An invoice is a tax document; rewriting one that has left the
building is a different category of problem from fixing a typo.
- **A number is assigned at issue, never at draft.** A gap in an invoice sequence is a question
from the tax office, so numbers are handed out only when a document actually becomes one.
- **Approval is a separate act from issuing.** `approved_by_id` records who read the narratives
the client is about to read. That review is the whole reason firms bill late and correctly
rather than early and wrong.
- **Client money can never go negative** — enforced by a CHECK constraint on the balance, so a
bug in this file cannot overdraw a client's funds.
Rounding: VAT is computed per line and rounded half-up to the grosz, then summed. Summing net
first and taxing the total gives a different (and, for the client, occasionally worse) answer;
per-line is what accounting software and the tax authority expect.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import func, select
from sqlalchemy.orm import Session as DbSession
from ..enums import (
DepositMovementKind,
ExpenseKind,
InvoiceKind,
InvoiceStatus,
NodeRole,
)
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import (
AppUser,
ClientDeposit,
DepositMovement,
Expense,
Invoice,
InvoiceLine,
Matter,
TimeEntry,
)
from . import matters as matters_svc, settings as settings_svc
# Recharged at cost, so no VAT of ours rides on them.
PASSTHROUGH_KINDS = frozenset({ExpenseKind.court_fee, ExpenseKind.stamp_duty})
DEFAULT_VAT_RATE = 23
DEFAULT_PAYMENT_DAYS = 14
# Statuses in which an invoice may still be changed.
MUTABLE = frozenset({InvoiceStatus.draft, InvoiceStatus.approved})
def _round_half_up(value: float) -> int:
"""Grosze, rounded half-up — the convention Polish invoices use."""
return int(value + 0.5) if value >= 0 else -int(-value + 0.5)
def vat_of(net_minor: int, rate: int) -> int:
return _round_half_up(net_minor * rate / 100)
# ── expenses ──────────────────────────────────────────────────────────────────
def get_expense(db: DbSession, expense_id: uuid.UUID) -> Expense:
row = db.get(Expense, expense_id)
if row is None:
raise NotFoundError("Nie znaleziono wydatku.")
return row
def add_expense(
db: DbSession, user: AppUser, matter: Matter, *, kind: ExpenseKind, description: str,
amount_minor: int, spent_on: dt.date | None = None, billable: bool = True,
is_passthrough: bool | None = None, paid_from_deposit: bool = False, **fields
) -> Expense:
description = (description or "").strip()
if not description:
raise ValidationError("Opis wydatku jest wymagany.")
if not amount_minor or int(amount_minor) <= 0:
raise ValidationError("Kwota wydatku musi być dodatnia.")
row = Expense(
matter_id=matter.id, kind=kind, description=description,
amount_minor=int(amount_minor), spent_on=spent_on or dt.date.today(),
billable=billable, paid_from_deposit=paid_from_deposit,
is_passthrough=(kind in PASSTHROUGH_KINDS if is_passthrough is None
else bool(is_passthrough)),
created_by_id=user.id,
**{k: v for k, v in fields.items() if v is not None},
)
db.add(row)
db.flush()
if paid_from_deposit:
# Paying a court fee out of money the client already lodged is a movement on their
# ledger, not a firm cost — so it has to hit the deposit or the balance is a fiction.
move_deposit(db, user, matter, amount_minor=-int(amount_minor),
kind=DepositMovementKind.expense,
description=f"{description}", expense_id=row.id)
return row
def delete_expense(db: DbSession, expense: Expense) -> None:
if expense.invoice_id is not None:
raise ConflictError("Ten wydatek jest na fakturze — usuń go najpierw z faktury.")
db.delete(expense)
def expenses_for(db: DbSession, matter: Matter) -> list[Expense]:
return list(
db.scalars(
select(Expense).where(Expense.matter_id == matter.id)
.order_by(Expense.spent_on.desc(), Expense.created_at.desc())
).all()
)
# ── client money ──────────────────────────────────────────────────────────────
def deposit_for(db: DbSession, matter: Matter, create: bool = False) -> ClientDeposit | None:
row = db.scalar(select(ClientDeposit).where(ClientDeposit.matter_id == matter.id))
if row is None and create:
row = ClientDeposit(matter_id=matter.id, currency=matter.currency, balance_minor=0)
db.add(row)
db.flush()
return row
def movements(db: DbSession, deposit: ClientDeposit) -> list[DepositMovement]:
return list(
db.scalars(
select(DepositMovement).where(DepositMovement.deposit_id == deposit.id)
.order_by(DepositMovement.created_at.desc())
).all()
)
def move_deposit(
db: DbSession, user: AppUser, matter: Matter, *, amount_minor: int,
kind: DepositMovementKind, description: str | None = None,
invoice_id: uuid.UUID | None = None, expense_id: uuid.UUID | None = None,
) -> DepositMovement:
"""Signed movement on a matter's client-money ledger. Refuses to overdraw."""
amount_minor = int(amount_minor)
if amount_minor == 0:
raise ValidationError("Kwota ruchu nie może być zerowa.")
deposit = deposit_for(db, matter, create=True)
new_balance = deposit.balance_minor + amount_minor
if new_balance < 0:
raise ConflictError(
f"Brak środków na depozycie: saldo {deposit.balance_minor / 100:.2f}, "
f"próba pobrania {abs(amount_minor) / 100:.2f}."
)
deposit.balance_minor = new_balance
row = DepositMovement(
deposit_id=deposit.id, kind=kind, amount_minor=amount_minor,
balance_after_minor=new_balance, description=description,
invoice_id=invoice_id, expense_id=expense_id, created_by_id=user.id,
)
db.add(row)
db.flush()
return row
# ── invoices ──────────────────────────────────────────────────────────────────
def get_invoice(db: DbSession, invoice_id: uuid.UUID) -> Invoice:
row = db.get(Invoice, invoice_id)
if row is None:
raise NotFoundError("Nie znaleziono faktury.")
return row
def lines_of(db: DbSession, invoice: Invoice) -> list[InvoiceLine]:
return list(
db.scalars(
select(InvoiceLine).where(InvoiceLine.invoice_id == invoice.id)
.order_by(InvoiceLine.position)
).all()
)
def next_number(db: DbSession, on_date: dt.date) -> str:
"""FV 0001/2026 — sequential within the year, derived from the highest issued number so a
restored backup cannot hand the same one out twice."""
suffix = f"/{on_date.year}"
highest = db.scalar(
select(func.max(Invoice.number)).where(Invoice.number.like(f"FV %{suffix}"))
)
seq = 1
if highest:
head = highest.split("/", 1)[0].replace("FV", "").strip()
if head.isdigit():
seq = int(head) + 1
return f"FV {seq:04d}{suffix}"
def unbilled(db: DbSession, matter: Matter) -> tuple[list[TimeEntry], list[Expense]]:
entries = list(
db.scalars(
select(TimeEntry).where(
TimeEntry.matter_id == matter.id,
TimeEntry.invoice_id.is_(None),
TimeEntry.billable.is_(True),
).order_by(TimeEntry.work_date)
).all()
)
costs = list(
db.scalars(
select(Expense).where(
Expense.matter_id == matter.id,
Expense.invoice_id.is_(None),
Expense.billable.is_(True),
).order_by(Expense.spent_on)
).all()
)
return [e for e in entries if e.billable_minutes > 0], costs
def draft_from_unbilled(
db: DbSession, user: AppUser, matter: Matter, *, group_time: bool = True,
vat_rate: int | None = None, note: str | None = None,
) -> Invoice:
"""Build a draft from everything unbilled on the matter.
`group_time` puts all time on one line (what most clients receive) rather than one line per
entry; the narratives are still attached to the entries either way, so a client who asks for
the detail gets it without the invoice becoming four pages."""
entries, costs = unbilled(db, matter)
if not entries and not costs:
raise ConflictError("Nie ma czego zafakturować — brak nierozliczonego czasu i wydatków.")
rate = DEFAULT_VAT_RATE if vat_rate is None else int(vat_rate)
if not 0 <= rate <= 100:
raise ValidationError("Stawka VAT musi mieścić się w przedziale 0–100.")
invoice = Invoice(
matter_id=matter.id, client_party_id=matter.client_party_id,
kind=InvoiceKind.invoice, status=InvoiceStatus.draft,
currency=matter.currency, note=note, created_by_id=user.id,
)
db.add(invoice)
db.flush()
position = 0
if entries:
if group_time:
minutes = sum(e.billable_minutes for e in entries)
amount = sum(e.amount_minor for e in entries)
position += 1
_add_line(
db, invoice, position,
description=f"Obsługa prawna — {matter.name}",
quantity_milli=int(round(minutes / 60 * 1000)), unit="h",
net_minor=amount, vat_rate=rate,
)
else:
for entry in entries:
position += 1
_add_line(
db, invoice, position,
description=f"{entry.work_date.isoformat()} — {entry.narrative}",
quantity_milli=int(round(entry.billable_minutes / 60 * 1000)), unit="h",
net_minor=entry.amount_minor, vat_rate=rate,
)
for entry in entries:
entry.invoice_id = invoice.id
for cost in costs:
position += 1
_add_line(
db, invoice, position,
description=f"{cost.description}",
quantity_milli=1000, unit="szt.",
net_minor=cost.amount_minor,
# A recharged court fee carries no VAT of ours.
vat_rate=0 if cost.is_passthrough else rate,
is_passthrough=cost.is_passthrough,
)
cost.invoice_id = invoice.id
recalculate(db, invoice)
return invoice
def _add_line(db: DbSession, invoice: Invoice, position: int, *, description: str,
quantity_milli: int, unit: str, net_minor: int, vat_rate: int,
is_passthrough: bool = False) -> InvoiceLine:
qty = max(quantity_milli, 1)
line = InvoiceLine(
invoice_id=invoice.id, position=position, description=description,
quantity_milli=qty, unit=unit,
unit_price_minor=int(round(net_minor / (qty / 1000))) if qty else net_minor,
net_minor=int(net_minor), vat_rate=int(vat_rate),
vat_minor=vat_of(int(net_minor), int(vat_rate)),
is_passthrough=is_passthrough,
)
line.gross_minor = line.net_minor + line.vat_minor
db.add(line)
db.flush()
return line
def recalculate(db: DbSession, invoice: Invoice) -> Invoice:
"""Totals from the lines. VAT is summed per line, never taxed on the total."""
rows = lines_of(db, invoice)
invoice.net_minor = sum(r.net_minor for r in rows)
invoice.vat_minor = sum(r.vat_minor for r in rows)
invoice.gross_minor = sum(r.gross_minor for r in rows)
db.flush()
return invoice
def assert_mutable(invoice: Invoice) -> None:
if invoice.status not in MUTABLE:
raise ConflictError(
"Faktura została wystawiona — popraw ją fakturą korygującą, nie edycją."
)
def approve(db: DbSession, invoice: Invoice, user: AppUser) -> Invoice:
"""A partner has read the narratives the client is about to read."""
if invoice.status != InvoiceStatus.draft:
raise ConflictError("Zatwierdzić można tylko projekt faktury.")
if not lines_of(db, invoice):
raise ConflictError("Faktura bez pozycji nie może zostać zatwierdzona.")
invoice.status = InvoiceStatus.approved
invoice.approved_by_id = user.id
invoice.approved_at = dt.datetime.now(dt.timezone.utc)
db.flush()
return invoice
def issue(db: DbSession, invoice: Invoice, user: AppUser, *, issued_on: dt.date | None = None,
payment_days: int | None = None) -> Invoice:
"""Assign a number and freeze the document."""
if invoice.status != InvoiceStatus.approved:
raise ConflictError("Fakturę można wystawić dopiero po zatwierdzeniu.")
issued_on = issued_on or dt.date.today()
invoice.number = next_number(db, issued_on)
invoice.issued_on = issued_on
invoice.sold_on = invoice.sold_on or issued_on
invoice.due_on = issued_on + dt.timedelta(
days=DEFAULT_PAYMENT_DAYS if payment_days is None else int(payment_days)
)
invoice.status = InvoiceStatus.issued
db.flush()
return invoice
def register_payment(db: DbSession, invoice: Invoice, *, amount_minor: int,
paid_on: dt.date | None = None) -> Invoice:
if invoice.status not in (InvoiceStatus.issued, InvoiceStatus.paid):
raise ConflictError("Płatność można zapisać tylko na wystawionej fakturze.")
amount_minor = int(amount_minor)
if amount_minor <= 0:
raise ValidationError("Kwota płatności musi być dodatnia.")
invoice.paid_minor += amount_minor
if invoice.paid_minor >= invoice.gross_minor:
invoice.status = InvoiceStatus.paid
invoice.paid_on = paid_on or dt.date.today()
db.flush()
return invoice
def settle_from_deposit(db: DbSession, invoice: Invoice, user: AppUser,
matter: Matter) -> Invoice:
"""Apply client money held on the matter against an issued invoice."""
if invoice.status != InvoiceStatus.issued:
raise ConflictError("Z depozytu rozlicza się fakturę wystawioną.")
outstanding = invoice.gross_minor - invoice.paid_minor
if outstanding <= 0:
raise ConflictError("Faktura jest już opłacona.")
deposit = deposit_for(db, matter, create=True)
take = min(outstanding, deposit.balance_minor)
if take <= 0:
raise ConflictError("Depozyt jest pusty.")
move_deposit(db, user, matter, amount_minor=-take,
kind=DepositMovementKind.applied,
description=f"Rozliczenie faktury {invoice.number or '(projekt)'}",
invoice_id=invoice.id)
return register_payment(db, invoice, amount_minor=take)
def cancel_draft(db: DbSession, invoice: Invoice) -> None:
"""Delete a draft and release everything it had locked."""
assert_mutable(invoice)
_release(db, invoice)
db.delete(invoice)
def _release(db: DbSession, invoice: Invoice) -> None:
for entry in db.scalars(select(TimeEntry).where(TimeEntry.invoice_id == invoice.id)).all():
entry.invoice_id = None
for cost in db.scalars(select(Expense).where(Expense.invoice_id == invoice.id)).all():
cost.invoice_id = None
db.flush()
def credit_note(db: DbSession, invoice: Invoice, user: AppUser, *,
reason: str) -> Invoice:
"""A full credit note against an issued invoice — the only way to correct one.
Mirrors every line with the sign flipped and releases the underlying time and expenses, so
the work can be re-billed correctly rather than written off by accident."""
if invoice.status not in (InvoiceStatus.issued, InvoiceStatus.paid):
raise ConflictError("Korygować można tylko wystawioną fakturę.")
if invoice.kind == InvoiceKind.credit_note:
raise ConflictError("Nie wystawia się korekty do korekty.")
existing = db.scalar(
select(Invoice).where(Invoice.corrects_invoice_id == invoice.id)
)
if existing is not None:
raise ConflictError("Do tej faktury wystawiono już korektę.")
if not (reason or "").strip():
raise ValidationError("Przyczyna korekty jest wymagana.")
note = Invoice(
matter_id=invoice.matter_id, client_party_id=invoice.client_party_id,
kind=InvoiceKind.credit_note, status=InvoiceStatus.approved,
currency=invoice.currency, corrects_invoice_id=invoice.id,
note=reason.strip(), created_by_id=user.id,
approved_by_id=user.id, approved_at=dt.datetime.now(dt.timezone.utc),
)
db.add(note)
db.flush()
for line in lines_of(db, invoice):
mirrored = InvoiceLine(
invoice_id=note.id, position=line.position,
description=f"Korekta: {line.description}",
quantity_milli=line.quantity_milli, unit=line.unit,
unit_price_minor=-line.unit_price_minor, net_minor=-line.net_minor,
vat_rate=line.vat_rate, vat_minor=-line.vat_minor,
gross_minor=-line.gross_minor, is_passthrough=line.is_passthrough,
)
db.add(mirrored)
db.flush()
recalculate(db, note)
invoice.status = InvoiceStatus.cancelled
_release(db, invoice)
db.flush()
return note
def for_matter(db: DbSession, matter: Matter) -> list[Invoice]:
return list(
db.scalars(
select(Invoice).where(Invoice.matter_id == matter.id)
.order_by(Invoice.created_at.desc())
).all()
)
def assert_can_bill(db: DbSession, user: AppUser, matter: Matter) -> None:
"""Money is an approver's business. Recording time is editor-level; deciding what a client
is asked to pay is not."""
matters_svc.assert_role(db, user, matter, NodeRole.approver)
# ── the numbers partners ask for ──────────────────────────────────────────────
def matter_financials(db: DbSession, matter: Matter) -> dict:
"""WIP, billed, paid and client money for one matter."""
entries, costs = unbilled(db, matter)
invoices = for_matter(db, matter)
live = [i for i in invoices if i.status != InvoiceStatus.cancelled]
issued = [i for i in live if i.status in (InvoiceStatus.issued, InvoiceStatus.paid)]
deposit = deposit_for(db, matter)
billed = sum(i.gross_minor for i in issued)
paid = sum(i.paid_minor for i in issued)
return {
"wip_minor": sum(e.amount_minor for e in entries),
"wip_minutes": sum(e.billable_minutes for e in entries),
"unbilled_expenses_minor": sum(c.amount_minor for c in costs),
"billed_minor": billed,
"paid_minor": paid,
"outstanding_minor": billed - paid,
"deposit_minor": deposit.balance_minor if deposit else 0,
"invoice_count": len(live),
}
def firm_summary(db: DbSession, user: AppUser) -> dict:
"""Firm-wide WIP and debt, filtered to the matters this user may read.
Deliberately computed over the readable set rather than the whole database: a partner's
dashboard should not leak the existence of a matter they are walled off from."""
from . import authz
from ..models import Node
all_matters = list(db.scalars(select(Matter)).all())
if not all_matters:
return {"wip_minor": 0, "outstanding_minor": 0, "overdue_minor": 0,
"deposits_minor": 0, "matters": 0}
nodes = list(
db.scalars(select(Node).where(Node.id.in_({m.node_id for m in all_matters}))).all()
)
readable = authz.readable_node_ids(db, user, nodes)
visible = [m for m in all_matters if m.node_id in readable]
today = dt.date.today()
wip = outstanding = overdue = deposits = 0
for matter in visible:
figures = matter_financials(db, matter)
wip += figures["wip_minor"] + figures["unbilled_expenses_minor"]
outstanding += figures["outstanding_minor"]
deposits += figures["deposit_minor"]
for invoice in db.scalars(
select(Invoice).where(Invoice.status == InvoiceStatus.issued)
).all():
if invoice.due_on and invoice.due_on < today and invoice.matter_id in {
m.id for m in visible
}:
overdue += invoice.gross_minor - invoice.paid_minor
return {
"wip_minor": wip,
"outstanding_minor": outstanding,
"overdue_minor": overdue,
"deposits_minor": deposits,
"matters": len(visible),
}
+242
View File
@@ -0,0 +1,242 @@
"""The conflict-of-interest engine.
This is the reason a firm buys a legal system instead of a generic CRM, so it is a blocking
gate rather than a report: `matters.open_matter` refuses to run without a decided check.
What it looks for, in the order that matters:
- **`client_conflict`** — a name we are asked to act AGAINST is an existing or former CLIENT.
The classic, career-ending one.
- **`adverse_conflict`** — the proposed CLIENT is already an adverse party in one of our
matters. Acting for someone we are simultaneously suing.
- **`related_entity`** — the same, reached one hop along `party_link` (parent company,
beneficial owner, spouse). Names never match here, which is exactly why it must be automatic.
- **`known_party`** — informational: we already hold a record for this name.
Every hit is frozen into `conflict_check.hits` as plain JSON, so the record still reads
correctly years later after parties have been renamed, merged or deleted. The row is never
edited after a decision (invariant 6) — to change an outcome, run a new check.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import or_, select
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
# 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.
MATCH_THRESHOLD = 0.6
SEVERITY = {
"client_conflict": 3,
"adverse_conflict": 3,
"related_entity": 2,
"known_party": 1,
}
def split_names(raw: str | None) -> list[str]:
"""Adverse names arrive as free text — one per line, or comma-separated."""
if not raw:
return []
parts: list[str] = []
for line in raw.replace(";", "\n").split("\n"):
for chunk in line.split(","):
name = chunk.strip()
if name:
parts.append(name)
return parts
def _candidate_parties(db: DbSession, names: list[str]) -> dict[uuid.UUID, tuple[Party, str, float]]:
"""Parties whose name or any alias resembles one of `names`.
Two-stage on purpose: a cheap SQL prefix filter on the first stem narrows the table, then
the scoring runs in Python. A trigram index would be better and is the Phase 3 upgrade;
at a small firm's data volume this is not the bottleneck."""
found: dict[uuid.UUID, tuple[Party, str, float]] = {}
for name in names:
stems = parties_svc.stems(name)
if not stems:
continue
clauses = [Party.search_key.like(f"%{s}%") for s in stems]
alias_clauses = [PartyAlias.search_key.like(f"%{s}%") for s in stems]
rows = list(db.scalars(select(Party).where(or_(*clauses)).limit(200)).all())
alias_party_ids = db.scalars(
select(PartyAlias.party_id).where(or_(*alias_clauses)).limit(200)
).all()
if alias_party_ids:
rows += list(db.scalars(select(Party).where(Party.id.in_(alias_party_ids))).all())
for party in rows:
score = parties_svc.similarity(name, party.name)
for alias in db.scalars(
select(PartyAlias.alias).where(PartyAlias.party_id == party.id)
).all():
score = max(score, parties_svc.similarity(name, alias))
if score >= MATCH_THRESHOLD:
previous = found.get(party.id)
if previous is None or score > previous[2]:
found[party.id] = (party, name, score)
return found
def _involvements(db: DbSession, party_ids: set[uuid.UUID]) -> list[tuple[MatterParty, Matter]]:
if not party_ids:
return []
return list(
db.execute(
select(MatterParty, Matter)
.join(Matter, Matter.id == MatterParty.matter_id)
.where(MatterParty.party_id.in_(party_ids))
).all()
)
def search(db: DbSession, *, subject: str, adverse_names: str | None) -> list[dict]:
"""Run the search and return the hits, most severe first. Pure read — no rows written,
so the intake screen can preview a check before committing to a record."""
subject = (subject or "").strip()
if not subject:
raise ValidationError("Podaj nazwę klienta do sprawdzenia.")
adverse = split_names(adverse_names)
subject_hits = _candidate_parties(db, [subject])
adverse_hits = _candidate_parties(db, adverse) if adverse else {}
# One hop out, so a parent company or beneficial owner is caught even though no name matches.
related_ids = parties_svc.related_party_ids(
db, set(subject_hits) | set(adverse_hits)
)
related_parties = (
{p.id: p for p in db.scalars(select(Party).where(Party.id.in_(related_ids))).all()}
if related_ids else {}
)
all_ids = set(subject_hits) | set(adverse_hits) | set(related_parties)
involvements = _involvements(db, all_ids)
by_party: dict[uuid.UUID, list[tuple[MatterParty, Matter]]] = {}
for mp, matter in involvements:
by_party.setdefault(mp.party_id, []).append((mp, matter))
hits: list[dict] = []
def _emit(party: Party, kind: str, matched_name: str, score: float, mp=None, matter=None):
hits.append({
"kind": kind,
"severity": SEVERITY[kind],
"party_id": str(party.id),
"party_name": party.name,
"matched_name": matched_name,
"score": round(score, 2),
"matter_id": str(matter.id) if matter else None,
"matter_reference": matter.reference if matter else None,
"matter_name": matter.name if matter else None,
"matter_status": matter.status.value if matter else None,
"role": mp.role.value if mp else None,
"is_adverse": bool(mp.is_adverse) if mp else None,
})
# A name we'd be acting against is one of our clients.
for pid, (party, matched, score) in adverse_hits.items():
rows = by_party.get(pid, [])
emitted = False
for mp, matter in rows:
if not mp.is_adverse:
_emit(party, "client_conflict", matched, score, mp, matter)
emitted = True
if not emitted:
_emit(party, "known_party", matched, score)
# Our proposed client is an adverse party somewhere.
for pid, (party, matched, score) in subject_hits.items():
rows = by_party.get(pid, [])
emitted = False
for mp, matter in rows:
if mp.is_adverse:
_emit(party, "adverse_conflict", matched, score, mp, matter)
emitted = True
if not emitted:
_emit(party, "known_party", matched, score)
# Reached only through a relationship — no name match, which is the point.
for pid, party in related_parties.items():
if pid in subject_hits or pid in adverse_hits:
continue
for mp, matter in by_party.get(pid, []):
_emit(party, "related_entity", party.name, 1.0, mp, matter)
hits.sort(key=lambda h: (-h["severity"], -h["score"], h["party_name"]))
return hits
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
real hit stays `pending` until a human decides, because a machine cannot waive a conflict."""
hits = search(db, subject=subject, adverse_names=adverse_names)
blocking = [h for h in hits if h["severity"] >= SEVERITY["related_entity"]]
check = ConflictCheck(
subject=subject.strip(),
adverse_names=(adverse_names or "").strip() or None,
hits=hits,
hit_count=len(hits),
outcome=ConflictOutcome.pending if blocking else ConflictOutcome.clear,
lead_id=lead_id,
run_by=user.id,
)
if not blocking:
check.decided_by = user.id
check.decided_at = dt.datetime.now(dt.timezone.utc)
check.decision_note = "Brak trafień — automatycznie."
db.add(check)
db.flush()
return check
def get(db: DbSession, check_id: uuid.UUID) -> ConflictCheck:
check = db.get(ConflictCheck, check_id)
if check is None:
raise NotFoundError("Nie znaleziono sprawdzenia konfliktu.")
return check
def decide(db: DbSession, check: ConflictCheck, user: AppUser, *,
outcome: ConflictOutcome, note: str | None) -> ConflictCheck:
"""Record the human decision. Once decided, a check is immutable — run a new one instead."""
if check.outcome != ConflictOutcome.pending:
raise ConflictError(
"To sprawdzenie zostało już rozstrzygnięte. Uruchom nowe zamiast zmieniać zapis."
)
if outcome == ConflictOutcome.pending:
raise ValidationError("Wybierz rozstrzygnięcie.")
if outcome in (ConflictOutcome.waived, ConflictOutcome.declined) and not (note or "").strip():
raise ValidationError("Uzasadnienie jest wymagane przy zgodzie lub odmowie.")
check.outcome = outcome
check.decision_note = (note or "").strip() or None
check.decided_by = user.id
check.decided_at = dt.datetime.now(dt.timezone.utc)
db.flush()
return check
def recent(db: DbSession, limit: int = 50) -> list[ConflictCheck]:
return list(
db.scalars(
select(ConflictCheck).order_by(ConflictCheck.created_at.desc()).limit(limit)
).all()
)
def pending_count(db: DbSession) -> int:
return len(
db.scalars(
select(ConflictCheck.id).where(ConflictCheck.outcome == ConflictOutcome.pending)
).all()
)
+299
View File
@@ -0,0 +1,299 @@
"""Correspondence: the inbox, assignment to a matter, and deadlines derived from a service date.
Two rules carry the weight, and both exist because a court letter attached to the wrong file or
counted from the wrong day is the failure mode that ends careers:
- **Assignment is a human act.** Items land unassigned. Nothing guesses which matter a letter
belongs to, because a plausible guess is worse than an empty inbox.
- **`legal_service_date` is set once and never inferred** (invariant 7). It can be corrected
while nothing depends on it; once a deadline has been derived from it, the correction is
refused and the user is told to remove those deadlines first. Silently moving a date that six
deadlines were computed from is how a firm misses all six.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import func, select
from sqlalchemy.orm import Session as DbSession
from ..enums import (
CorrespondenceChannel,
CorrespondenceDirection,
CorrespondenceStatus,
DeadlineKind,
DeadlineSource,
NodeRole,
)
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, Correspondence, Deadline, Matter, Node
from . import authz, deadlines as deadlines_svc, matters as matters_svc
# Channels that carry a legally binding service date. A `post` item does too, but somebody has
# to read the awizo and type it; these two are the ones Phase 2 reads automatically.
AUTHORITATIVE_CHANNELS = frozenset({
CorrespondenceChannel.edoreczenia,
CorrespondenceChannel.court_portal,
})
# The default clock a court deadline runs on. Fourteen days is the common KPC period, but this
# is only a suggested value in the UI — nothing computes a deadline without someone typing the
# number, because the right period depends on the pleading.
DEFAULT_PERIOD_DAYS = 14
def get(db: DbSession, item_id: uuid.UUID) -> Correspondence:
item = db.get(Correspondence, item_id)
if item is None:
raise NotFoundError("Nie znaleziono korespondencji.")
return item
def find_by_external_ref(
db: DbSession, channel: CorrespondenceChannel, external_ref: str
) -> Correspondence | None:
"""The idempotency lookup a connector calls before inserting. Backed by the partial unique
index, so a re-poll can never duplicate an item even under a race."""
return db.scalar(
select(Correspondence).where(
Correspondence.channel == channel,
Correspondence.external_ref == external_ref,
)
)
def record(
db: DbSession,
user: AppUser | None,
*,
channel: CorrespondenceChannel,
subject: str,
direction: CorrespondenceDirection = CorrespondenceDirection.incoming,
legal_service_date: dt.date | None = None,
matter_id: uuid.UUID | None = None,
external_ref: str | None = None,
**fields,
) -> Correspondence:
"""Create an item. Used by the console today and by connectors in Phase 2 — same path,
so the connectors inherit the rules rather than re-implementing them."""
subject = (subject or "").strip()
if not subject:
raise ValidationError("Opis korespondencji jest wymagany.")
if external_ref and find_by_external_ref(db, channel, external_ref) is not None:
raise ConflictError("Ta przesyłka jest już zarejestrowana.")
if legal_service_date and legal_service_date > dt.date.today():
raise ValidationError("Data doręczenia nie może być w przyszłości.")
item = Correspondence(
channel=channel,
direction=direction,
subject=subject,
legal_service_date=legal_service_date,
matter_id=matter_id,
external_ref=external_ref or None,
status=(CorrespondenceStatus.assigned if matter_id
else CorrespondenceStatus.unassigned),
received_at=(dt.datetime.now(dt.timezone.utc)
if direction == CorrespondenceDirection.incoming else None),
created_by_id=user.id if user else None,
assigned_by_id=user.id if (user and matter_id) else None,
assigned_at=dt.datetime.now(dt.timezone.utc) if matter_id else None,
**{k: v for k, v in fields.items() if v is not None},
)
db.add(item)
db.flush()
return item
def derived_deadlines(db: DbSession, item: Correspondence) -> list[Deadline]:
return list(
db.scalars(
select(Deadline).where(Deadline.source_correspondence_id == item.id)
.order_by(Deadline.due_date)
).all()
)
def set_service_date(
db: DbSession, item: Correspondence, user: AppUser, service_date: dt.date
) -> Correspondence:
"""Set or correct the legally binding service date.
Refused once a deadline has been derived from it — see the module docstring. The caller
should surface the derived deadlines so the user can see exactly what they would be moving.
"""
if service_date is None:
raise ValidationError("Podaj datę doręczenia.")
if service_date > dt.date.today():
raise ValidationError("Data doręczenia nie może być w przyszłości.")
if item.legal_service_date == service_date:
return item
if item.legal_service_date is not None:
existing = derived_deadlines(db, item)
if existing:
raise ConflictError(
f"Od tej daty policzono już {len(existing)} termin(y). Usuń je najpierw — "
"cicha zmiana daty przesunęłaby wszystkie naraz."
)
item.legal_service_date = service_date
db.flush()
return item
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."""
matters_svc.assert_role(db, user, matter, NodeRole.editor)
item.matter_id = matter.id
item.status = CorrespondenceStatus.assigned
item.assigned_by_id = user.id
item.assigned_at = dt.datetime.now(dt.timezone.utc)
db.flush()
return item
def unassign(db: DbSession, item: Correspondence) -> Correspondence:
"""Send an item back to the inbox — a misfiling correction."""
if derived_deadlines(db, item):
raise ConflictError(
"Od tej korespondencji policzono terminy. Usuń je przed odpięciem od sprawy."
)
item.matter_id = None
item.status = CorrespondenceStatus.unassigned
item.assigned_by_id = None
item.assigned_at = None
db.flush()
return item
def set_status(db: DbSession, item: Correspondence, status: CorrespondenceStatus):
if status == CorrespondenceStatus.assigned and item.matter_id is None:
raise ValidationError("Najpierw przypisz korespondencję do sprawy.")
item.status = status
db.flush()
return item
def delete(db: DbSession, item: Correspondence) -> None:
if derived_deadlines(db, item):
raise ConflictError(
"Od tej korespondencji policzono terminy — usuń je najpierw. "
"Termin bez dokumentu, z którego wynika jego data, jest gorszy niż brak terminu."
)
db.delete(item)
def derive_deadline(
db: DbSession,
user: AppUser,
item: Correspondence,
*,
title: str,
kind: DeadlineKind,
source: DeadlineSource,
days: int,
owner_id: uuid.UUID | None = None,
) -> Deadline:
"""Compute a deadline from this item's service date, linked back to it.
The link is the point: `deadline.basis` says how the date was reached in words, and
`source_correspondence_id` lets anyone open the document it was reached from."""
if item.matter_id is None:
raise ConflictError("Najpierw przypisz korespondencję do sprawy.")
if item.legal_service_date is None:
raise ConflictError(
"Ta przesyłka nie ma jeszcze daty doręczenia — bez niej nie ma od czego liczyć."
)
matter = matters_svc.get_matter(db, item.matter_id)
matters_svc.assert_role(db, user, matter, NodeRole.editor)
return deadlines_svc.derive(
db, user, matter, title=title, kind=kind, source=source,
service_date=item.legal_service_date, days=days,
correspondence_id=item.id, owner_id=owner_id,
)
# ── reads ─────────────────────────────────────────────────────────────────────
def inbox(db: DbSession, limit: int = 200) -> list[Correspondence]:
"""Unassigned incoming items, oldest first — the ones with a service date at the top,
because those are already counting."""
return list(
db.scalars(
select(Correspondence)
.where(
Correspondence.status == CorrespondenceStatus.unassigned,
Correspondence.direction == CorrespondenceDirection.incoming,
)
.order_by(
Correspondence.legal_service_date.is_(None),
Correspondence.legal_service_date,
Correspondence.created_at,
)
.limit(limit)
).all()
)
def _undated_where():
return (
Correspondence.direction == CorrespondenceDirection.incoming,
Correspondence.legal_service_date.is_(None),
Correspondence.channel.in_(tuple(AUTHORITATIVE_CHANNELS)),
)
def undated(db: DbSession, limit: int = 50) -> list[Correspondence]:
"""Incoming items from an authoritative channel with no service date yet. Every one of
these is a clock that may already be running while nobody is watching it.
Oldest first — the longest-ignored are the most dangerous. Callers that need to act on ALL
of them (the reminder engine) must pass their own limit; callers that need the total must
use `count_undated`, because `len()` of a truncated list is a number that quietly lies."""
return list(
db.scalars(
select(Correspondence).where(*_undated_where())
.order_by(Correspondence.created_at)
.limit(limit)
).all()
)
def count_undated(db: DbSession) -> int:
return int(db.scalar(select(func.count()).select_from(Correspondence)
.where(*_undated_where())) or 0)
def count_inbox(db: DbSession) -> int:
return int(
db.scalar(
select(func.count()).select_from(Correspondence).where(
Correspondence.status == CorrespondenceStatus.unassigned,
Correspondence.direction == CorrespondenceDirection.incoming,
)
)
or 0
)
def for_matter(db: DbSession, matter: Matter) -> list[Correspondence]:
return list(
db.scalars(
select(Correspondence).where(Correspondence.matter_id == matter.id)
.order_by(Correspondence.legal_service_date.desc().nullslast(),
Correspondence.created_at.desc())
).all()
)
def visible_for_matter_ids(db: DbSession, user: AppUser, items: list[Correspondence]) -> set:
"""Filter assigned items to matters the user may read. Unassigned items stay visible: an
inbox nobody can see is an inbox nobody empties, and an unfiled letter is not yet
privileged to any particular matter."""
matter_ids = {i.matter_id for i in items if i.matter_id}
if not matter_ids:
return set()
found = list(db.scalars(select(Matter).where(Matter.id.in_(matter_ids))).all())
node_ids = {m.node_id for m in found}
nodes = list(db.scalars(select(Node).where(Node.id.in_(node_ids))).all())
readable = authz.readable_node_ids(db, user, nodes)
return {m.id for m in found if m.node_id in readable}
+199
View File
@@ -0,0 +1,199 @@
"""Deadlines (terminy) and court events.
Two rules carry the weight here:
- **Dual control.** A statutory or court deadline is not "managed" until a second person has
confirmed it. `confirm()` refuses the creator, because a four-eyes check performed by one
pair of eyes is theatre.
- **Traceability.** Every derived deadline records, in words, how its date was reached
("doręczenie 2026-08-03 + 14 dni") and points at the correspondence row that started the
clock. When Phase 2 wires e-Doręczenia in, `derive()` is the function it calls.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import DeadlineKind, DeadlineSource
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, CourtEvent, Deadline, Matter, Node
# Sources where a missed date is malpractice rather than an inconvenience.
DUAL_CONTROL_SOURCES = frozenset({DeadlineSource.statute, DeadlineSource.court})
def get_deadline(db: DbSession, deadline_id: uuid.UUID) -> Deadline:
row = db.get(Deadline, deadline_id)
if row is None:
raise NotFoundError("Nie znaleziono terminu.")
return row
def create(
db: DbSession,
user: AppUser,
matter: Matter,
*,
title: str,
kind: DeadlineKind,
source: DeadlineSource,
due_date: dt.date,
basis: str | None = None,
owner_id: uuid.UUID | None = None,
source_correspondence_id: uuid.UUID | None = None,
notes: str | None = None,
) -> Deadline:
title = (title or "").strip()
if not title:
raise ValidationError("Opis terminu jest wymagany.")
if due_date is None:
raise ValidationError("Data terminu jest wymagana.")
row = Deadline(
matter_id=matter.id, title=title, kind=kind, source=source, due_date=due_date,
basis=basis, owner_id=owner_id or user.id, created_by_id=user.id,
source_correspondence_id=source_correspondence_id, notes=notes,
)
db.add(row)
db.flush()
return row
def derive(
db: DbSession,
user: AppUser,
matter: Matter,
*,
title: str,
kind: DeadlineKind,
source: DeadlineSource,
service_date: dt.date,
days: int,
correspondence_id: uuid.UUID | None = None,
owner_id: uuid.UUID | None = None,
) -> Deadline:
"""Create a deadline computed from a service date.
Calendar days, which is the KPC default. Business-day and court-holiday handling belongs
with the e-Doręczenia work in Phase 2, when there is a real service date to compute from —
guessing at the rules before then would produce dates a lawyer cannot check."""
if days <= 0:
raise ValidationError("Liczba dni musi być dodatnia.")
due = service_date + dt.timedelta(days=days)
basis = f"doręczenie {service_date.isoformat()} + {days} dni"
return create(
db, user, matter, title=title, kind=kind, source=source, due_date=due,
basis=basis, owner_id=owner_id, source_correspondence_id=correspondence_id,
)
def confirm(db: DbSession, deadline: Deadline, user: AppUser) -> Deadline:
"""Second-person confirmation. Refuses the creator for statutory and court deadlines."""
if deadline.confirmed_at is not None:
raise ConflictError("Ten termin został już potwierdzony.")
if deadline.source in DUAL_CONTROL_SOURCES and deadline.created_by_id == user.id:
raise ConflictError(
"Termin ustawowy lub sądowy musi potwierdzić inna osoba niż ta, która go wprowadziła."
)
deadline.confirmed_by_id = user.id
deadline.confirmed_at = dt.datetime.now(dt.timezone.utc)
db.flush()
return deadline
def complete(db: DbSession, deadline: Deadline, user: AppUser) -> Deadline:
if deadline.completed_at is not None:
return deadline
deadline.completed_at = dt.datetime.now(dt.timezone.utc)
deadline.completed_by_id = user.id
db.flush()
return deadline
def reopen(db: DbSession, deadline: Deadline) -> Deadline:
deadline.completed_at = None
deadline.completed_by_id = None
db.flush()
return deadline
def for_matter(db: DbSession, matter: Matter, *, include_done: bool = False) -> list[Deadline]:
stmt = select(Deadline).where(Deadline.matter_id == matter.id)
if not include_done:
stmt = stmt.where(Deadline.completed_at.is_(None))
return list(db.scalars(stmt.order_by(Deadline.due_date)).all())
def upcoming(
db: DbSession, user: AppUser, *, days: int = 14, mine: bool = False, limit: int = 100
) -> list[tuple[Deadline, Matter]]:
"""Open deadlines due within `days`, plus anything already overdue, filtered to what the
user may read. Overdue is never hidden — it is the whole point of the screen."""
from . import authz
horizon = dt.date.today() + dt.timedelta(days=days)
stmt = (
select(Deadline, Matter)
.join(Matter, Matter.id == Deadline.matter_id)
.where(Deadline.completed_at.is_(None), Deadline.due_date <= horizon)
.order_by(Deadline.due_date)
.limit(limit)
)
if mine:
stmt = stmt.where(Deadline.owner_id == user.id)
rows = list(db.execute(stmt).all())
if not rows:
return []
node_ids = {m.node_id for _, m in rows}
found = list(db.scalars(select(Node).where(Node.id.in_(node_ids))).all())
readable = authz.readable_node_ids(db, user, found)
return [(d, m) for d, m in rows if m.node_id in readable]
def unconfirmed(db: DbSession, user: AppUser, limit: int = 50) -> list[tuple[Deadline, Matter]]:
"""Deadlines that still need a second pair of eyes — the dashboard's first card."""
from . import authz
rows = list(
db.execute(
select(Deadline, Matter)
.join(Matter, Matter.id == Deadline.matter_id)
.where(
Deadline.confirmed_at.is_(None),
Deadline.completed_at.is_(None),
Deadline.source.in_(tuple(DUAL_CONTROL_SOURCES)),
)
.order_by(Deadline.due_date)
.limit(limit)
).all()
)
if not rows:
return []
node_ids = {m.node_id for _, m in rows}
found = list(db.scalars(select(Node).where(Node.id.in_(node_ids))).all())
readable = authz.readable_node_ids(db, user, found)
return [(d, m) for d, m in rows if m.node_id in readable]
# ── court events ──────────────────────────────────────────────────────────────
def create_event(db: DbSession, matter: Matter, *, title: str, starts_at: dt.datetime,
**fields) -> CourtEvent:
title = (title or "").strip()
if not title:
raise ValidationError("Opis wydarzenia jest wymagany.")
row = CourtEvent(matter_id=matter.id, title=title, starts_at=starts_at,
**{k: v for k, v in fields.items() if v is not None})
db.add(row)
db.flush()
return row
def events_for_matter(db: DbSession, matter: Matter) -> list[CourtEvent]:
return list(
db.scalars(
select(CourtEvent).where(CourtEvent.matter_id == matter.id)
.order_by(CourtEvent.starts_at)
).all()
)
+284
View File
@@ -0,0 +1,284 @@
"""Court fees (opłaty sądowe) and statutory representation costs (koszty zastępstwa procesowego).
Pure computation — no database, no I/O — so the whole thing is testable and every number can be
traced to a statute.
**This module contains legal data with a shelf life.** The schedules below are the fee tables
from the two sources named in `SOURCES`, and both get amended. They are therefore written as
plain data with the legal basis on every bracket, not buried in `if` statements, so a lawyer can
read the table and check it against the current text without reading Python. `SCHEDULE_VERSION`
says what they were last checked against.
**Verify before relying on the output.** These figures were assembled from working knowledge of
the statutes, not transcribed from an official text under review. Treat the arithmetic as
trustworthy and the numbers as needing a second pair of eyes — the same rule the product applies
to deadlines. The UI says so too.
Money is integer grosze throughout (invariant 12). Court fees round **up** to a full złoty,
which is art. 21 u.k.s.c. and not a rounding preference.
"""
from __future__ import annotations
import dataclasses
import datetime as dt
from decimal import ROUND_CEILING, Decimal
from ..errors import ValidationError
SCHEDULE_VERSION = "2026-08"
VERIFY_NOTE = (
"Stawki wymagają sprawdzenia z aktualnym brzmieniem u.k.s.c. i rozporządzenia MS. "
"Wynik jest szacunkiem, nie opinią prawną."
)
SOURCES = (
"Ustawa z 28.07.2005 r. o kosztach sądowych w sprawach cywilnych (u.k.s.c.)",
"Rozporządzenie MS z 22.10.2015 r. w sprawie opłat za czynności adwokackie",
"Rozporządzenie MS z 22.10.2015 r. w sprawie opłat za czynności radców prawnych",
"Ustawa z 16.11.2006 r. o opłacie skarbowej",
)
GROSZE = 100
MAX_VALUE_MINOR = 10**13 # 100 mld zł — a guard against a typo, not a legal limit
# ── opłata sądowa (u.k.s.c.) ──────────────────────────────────────────────────
@dataclasses.dataclass(frozen=True)
class Bracket:
"""Brackets are upper-inclusive: the statute reads "ponad 500 zł do 1500 zł"."""
up_to_minor: int | None # None = no upper bound
amount_minor: int
basis: str
# art. 13 ust. 1 u.k.s.c. — opłata stosunkowa, wartości stałe do 20 000 zł.
FIXED_BRACKETS: tuple[Bracket, ...] = (
Bracket(500_00, 30_00, "art. 13 ust. 1 pkt 1 u.k.s.c."),
Bracket(1_500_00, 100_00, "art. 13 ust. 1 pkt 2 u.k.s.c."),
Bracket(4_000_00, 200_00, "art. 13 ust. 1 pkt 3 u.k.s.c."),
Bracket(7_500_00, 400_00, "art. 13 ust. 1 pkt 4 u.k.s.c."),
Bracket(10_000_00, 500_00, "art. 13 ust. 1 pkt 5 u.k.s.c."),
Bracket(15_000_00, 750_00, "art. 13 ust. 1 pkt 6 u.k.s.c."),
Bracket(20_000_00, 1_000_00, "art. 13 ust. 1 pkt 7 u.k.s.c."),
)
# art. 13 ust. 2 u.k.s.c. — powyżej 20 000 zł: 5% wps, nie więcej niż 200 000 zł.
PROPORTIONAL_RATE = Decimal("0.05")
PROPORTIONAL_CAP_MINOR = 200_000_00
PROPORTIONAL_BASIS = "art. 13 ust. 2 u.k.s.c."
# art. 21 u.k.s.c. — końcówkę opłaty zaokrągla się w górę do pełnego złotego.
ROUNDING_BASIS = "art. 21 u.k.s.c."
OPLATA_SKARBOWA_PELNOMOCNICTWO_MINOR = 17_00 # ustawa o opłacie skarbowej, zał. cz. IV
@dataclasses.dataclass(frozen=True)
class Proceeding:
"""A kind of filing and the fraction of the base fee it attracts."""
key: str
label: str
numerator: int
denominator: int
basis: str
minimum_minor: int | None = None
PROCEEDINGS: tuple[Proceeding, ...] = (
Proceeding("pozew", "Pozew (postępowanie zwykłe)", 1, 1, "art. 13 u.k.s.c."),
Proceeding("nakazowy", "Pozew w postępowaniu nakazowym", 1, 4,
"art. 19 ust. 2 pkt 1 u.k.s.c."),
Proceeding("epu", "Pozew w EPU (e-sąd)", 1, 4, "art. 19 ust. 2 pkt 2 u.k.s.c."),
Proceeding("apelacja", "Apelacja", 1, 1, "art. 18 ust. 2 u.k.s.c."),
Proceeding("zazalenie", "Zażalenie", 1, 5, "art. 19 ust. 3 pkt 2 u.k.s.c."),
Proceeding("skarga_kasacyjna", "Skarga kasacyjna", 1, 1, "art. 18 ust. 2 u.k.s.c."),
)
PROCEEDING_BY_KEY = {p.key: p for p in PROCEEDINGS}
def _round_up_to_zloty(minor: int) -> int:
"""art. 21 u.k.s.c. — round the fee up to a whole złoty."""
return -(-int(minor) // GROSZE) * GROSZE
def _check_value(value_minor: int) -> int:
if value_minor is None:
raise ValidationError("Podaj wartość przedmiotu sporu.")
value_minor = int(value_minor)
if value_minor <= 0:
raise ValidationError("Wartość przedmiotu sporu musi być dodatnia.")
if value_minor > MAX_VALUE_MINOR:
raise ValidationError("Wartość przedmiotu sporu jest nierealnie wysoka — sprawdź wpis.")
return value_minor
def base_court_fee(value_minor: int) -> dict:
"""Opłata stosunkowa from the value in dispute, before any fraction is applied."""
value_minor = _check_value(value_minor)
for bracket in FIXED_BRACKETS:
if value_minor <= bracket.up_to_minor:
return {"amount_minor": bracket.amount_minor, "basis": bracket.basis,
"capped": False}
raw = Decimal(value_minor) * PROPORTIONAL_RATE
amount = int(raw.to_integral_value(rounding=ROUND_CEILING))
capped = amount > PROPORTIONAL_CAP_MINOR
return {
"amount_minor": min(_round_up_to_zloty(amount), PROPORTIONAL_CAP_MINOR),
"basis": PROPORTIONAL_BASIS,
"capped": capped,
}
def court_fee(value_minor: int, proceeding: str = "pozew") -> dict:
"""The fee actually payable on a given filing."""
item = PROCEEDING_BY_KEY.get(proceeding)
if item is None:
raise ValidationError(f"Nieznany rodzaj pisma: {proceeding}.")
base = base_court_fee(value_minor)
amount = base["amount_minor"] * item.numerator // item.denominator
amount = _round_up_to_zloty(amount)
if item.minimum_minor is not None:
amount = max(amount, item.minimum_minor)
return {
"proceeding": item.key,
"proceeding_label": item.label,
"value_minor": int(value_minor),
"base_minor": base["amount_minor"],
"fraction": f"{item.numerator}/{item.denominator}" if item.denominator != 1 else "1/1",
"amount_minor": amount,
"capped": base["capped"],
"basis": [base["basis"], item.basis, ROUNDING_BASIS],
}
# ── koszty zastępstwa procesowego (rozporządzenie MS z 22.10.2015) ────────────
# § 2 — stawki minimalne w sprawach o prawa majątkowe, według wartości przedmiotu sprawy.
REPRESENTATION_BRACKETS: tuple[Bracket, ...] = (
Bracket(500_00, 90_00, "§ 2 pkt 1"),
Bracket(1_500_00, 270_00, "§ 2 pkt 2"),
Bracket(5_000_00, 900_00, "§ 2 pkt 3"),
Bracket(10_000_00, 1_800_00, "§ 2 pkt 4"),
Bracket(50_000_00, 3_600_00, "§ 2 pkt 5"),
Bracket(200_000_00, 5_400_00, "§ 2 pkt 6"),
Bracket(2_000_000_00, 10_800_00, "§ 2 pkt 7"),
Bracket(5_000_000_00, 15_000_00, "§ 2 pkt 8"),
Bracket(None, 25_000_00, "§ 2 pkt 9"),
)
# § 15 ust. 3 — sąd może zasądzić wielokrotność stawki minimalnej, nie wyższą niż sześciokrotność.
MAX_MULTIPLIER = 6
@dataclasses.dataclass(frozen=True)
class Stage:
key: str
label: str
percent: int
basis: str
minimum_minor: int | None = None
STAGES: tuple[Stage, ...] = (
Stage("i_instancja", "I instancja", 100, "§ 2 (stawka minimalna)"),
Stage("apelacja_so", "Apelacja — sąd okręgowy", 50, "§ 10 ust. 1 pkt 1", 120_00),
Stage("apelacja_sa", "Apelacja — sąd apelacyjny", 75, "§ 10 ust. 1 pkt 2"),
Stage("kasacja", "Postępowanie kasacyjne", 75, "§ 10 ust. 4 pkt 1"),
Stage("zazalenie_so", "Zażalenie — sąd okręgowy", 25, "§ 10 ust. 2 pkt 1"),
Stage("zazalenie_sa", "Zażalenie — sąd apelacyjny / SN", 50, "§ 10 ust. 2 pkt 2"),
)
STAGE_BY_KEY = {s.key: s for s in STAGES}
def minimum_representation_fee(value_minor: int) -> dict:
value_minor = _check_value(value_minor)
for bracket in REPRESENTATION_BRACKETS:
if bracket.up_to_minor is None or value_minor <= bracket.up_to_minor:
return {"amount_minor": bracket.amount_minor, "basis": bracket.basis}
raise AssertionError("unreachable — the last bracket is unbounded") # pragma: no cover
def representation_costs(value_minor: int, stage: str = "i_instancja",
multiplier: int = 1) -> dict:
"""Statutory representation costs for one stage.
`multiplier` is the § 15 ust. 3 uplift a court *may* award (up to six times the minimum).
It defaults to 1 because that is what is normally awarded — anything above it is argued for,
not assumed."""
item = STAGE_BY_KEY.get(stage)
if item is None:
raise ValidationError(f"Nieznany etap postępowania: {stage}.")
# None means "not specified" → the minimum. 0 is a caller error, not a shorthand, so it is
# rejected rather than quietly turned into 1.
multiplier = 1 if multiplier is None else int(multiplier)
if multiplier < 1 or multiplier > MAX_MULTIPLIER:
raise ValidationError(
f"Krotność stawki musi mieścić się w przedziale 1–{MAX_MULTIPLIER} (§ 15 ust. 3)."
)
minimum = minimum_representation_fee(value_minor)
amount = minimum["amount_minor"] * item.percent // 100
if item.minimum_minor is not None:
amount = max(amount, item.minimum_minor)
amount *= multiplier
return {
"stage": item.key,
"stage_label": item.label,
"value_minor": int(value_minor),
"minimum_minor": minimum["amount_minor"],
"percent": item.percent,
"multiplier": multiplier,
"amount_minor": amount,
"basis": [minimum["basis"], item.basis]
+ (["§ 15 ust. 3"] if multiplier > 1 else []),
}
# ── the combined estimate the console shows ───────────────────────────────────
def estimate(
value_minor: int,
*,
proceeding: str = "pozew",
stage: str = "i_instancja",
multiplier: int = 1,
powers_of_attorney: int = 1,
) -> dict:
"""Everything a lawyer wants on one screen before filing: what it costs to file, what the
opponent would owe in representation costs if we win, and the stamp duty on the mandate."""
if powers_of_attorney < 0:
raise ValidationError("Liczba pełnomocnictw nie może być ujemna.")
fee = court_fee(value_minor, proceeding)
costs = representation_costs(value_minor, stage, multiplier)
stamp = powers_of_attorney * OPLATA_SKARBOWA_PELNOMOCNICTWO_MINOR
return {
"value_minor": int(value_minor),
"court_fee": fee,
"representation": costs,
"stamp_duty": {
"count": powers_of_attorney,
"unit_minor": OPLATA_SKARBOWA_PELNOMOCNICTWO_MINOR,
"amount_minor": stamp,
"basis": ["ustawa o opłacie skarbowej, zał. cz. IV"],
},
# What the client actually has to find before the case starts.
"upfront_minor": fee["amount_minor"] + stamp,
"schedule_version": SCHEDULE_VERSION,
"verify_note": VERIFY_NOTE,
"sources": list(SOURCES),
"generated_on": dt.date.today().isoformat(),
}
def options() -> dict:
"""The pickers the console renders, so the labels and legal bases live in one place."""
return {
"proceedings": [
{"key": p.key, "label": p.label,
"fraction": f"{p.numerator}/{p.denominator}", "basis": p.basis}
for p in PROCEEDINGS
],
"stages": [
{"key": s.key, "label": s.label, "percent": s.percent, "basis": s.basis}
for s in STAGES
],
"max_multiplier": MAX_MULTIPLIER,
"schedule_version": SCHEDULE_VERSION,
"verify_note": VERIFY_NOTE,
"sources": list(SOURCES),
}
+76
View File
@@ -0,0 +1,76 @@
"""Intake: enquiries (leads) before they are matters.
This is the CRM half. It stays deliberately thin — the value is not in a pipeline board, it is
in the fact that nothing crosses from enquiry to matter without passing the conflict gate.
"""
from __future__ import annotations
import uuid
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import LeadStage
from ..errors import NotFoundError, ValidationError
from ..models import AppUser, ConflictCheck, Lead
def get_lead(db: DbSession, lead_id: uuid.UUID) -> Lead:
row = db.get(Lead, lead_id)
if row is None:
raise NotFoundError("Nie znaleziono zapytania.")
return row
def create(db: DbSession, user: AppUser, *, name: str, **fields) -> Lead:
name = (name or "").strip()
if not name:
raise ValidationError("Nazwa klienta jest wymagana.")
row = Lead(
name=name,
owner_id=fields.pop("owner_id", None) or user.id,
**{k: v for k, v in fields.items() if v is not None},
)
db.add(row)
db.flush()
return row
def update(db: DbSession, lead: Lead, **fields) -> Lead:
for key, value in fields.items():
if value is not None and hasattr(lead, key):
setattr(lead, key, value)
db.flush()
return lead
def listing(db: DbSession, *, stage: LeadStage | None = None, limit: int = 200) -> list[Lead]:
stmt = select(Lead).order_by(Lead.created_at.desc()).limit(limit)
if stage is not None:
stmt = select(Lead).where(Lead.stage == stage).order_by(Lead.created_at.desc()).limit(limit)
return list(db.scalars(stmt).all())
def checks_for(db: DbSession, lead: Lead) -> list[ConflictCheck]:
"""Every conflict check run against this enquiry, newest first."""
return list(
db.scalars(
select(ConflictCheck)
.where(ConflictCheck.lead_id == lead.id)
.order_by(ConflictCheck.created_at.desc())
).all()
)
def mark_won(db: DbSession, lead: Lead, matter_id: uuid.UUID) -> Lead:
lead.stage = LeadStage.won
lead.matter_id = matter_id
db.flush()
return lead
def mark_lost(db: DbSession, lead: Lead, reason: str | None) -> Lead:
lead.stage = LeadStage.lost
lead.lost_reason = (reason or "").strip() or None
db.flush()
return lead
+310
View File
@@ -0,0 +1,310 @@
"""Matters (sprawy) — opening, reading, updating, and the parties on them.
Opening a matter is the one flow with real ceremony, and deliberately so:
1. a conflict check must exist and be decided `clear` or `waived`;
2. the check is consumed — one check opens one matter, so a `clear` result can't be reused
next month when the facts have changed;
3. a node of kind `matter` is created (the leaf, which is what permissions resolve through);
4. a case file is requested from Galena, best-effort.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session as DbSession
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, nodes as nodes_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.
ADVERSE_ROLES = frozenset({PartyRole.opponent, PartyRole.opponent_counsel})
def next_reference(db: DbSession, year: int | None = None) -> str:
"""Sequential per year: 2026/0001. Derived from the highest existing number rather than a
counter table, so a restored backup can't hand out a reference twice."""
year = year or dt.date.today().year
prefix = f"{year}/"
highest = db.scalar(
select(func.max(Matter.reference)).where(Matter.reference.like(f"{prefix}%"))
)
seq = 1
if highest:
tail = highest.split("/", 1)[1]
if tail.isdigit():
seq = int(tail) + 1
return f"{prefix}{seq:04d}"
def get_matter(db: DbSession, matter_id: uuid.UUID) -> Matter:
matter = db.get(Matter, matter_id)
if matter is None:
raise NotFoundError("Nie znaleziono sprawy.")
return matter
def get_by_node(db: DbSession, node_id: uuid.UUID) -> Matter | None:
return db.scalar(select(Matter).where(Matter.node_id == node_id))
def node_of(db: DbSession, matter: Matter) -> Node:
node = db.get(Node, matter.node_id)
if node is None: # pragma: no cover — FK + cascade make this unreachable
raise NotFoundError("Nie znaleziono sprawy.")
return node
def assert_can_read(db: DbSession, user: AppUser, matter: Matter) -> NodeRole:
return authz.assert_can_read(db, user, node_of(db, matter))
def assert_role(db: DbSession, user: AppUser, matter: Matter, minimum: NodeRole) -> NodeRole:
return authz.assert_role(db, user, node_of(db, matter), minimum)
def assert_wall_admin(db: DbSession, user: AppUser, matter: Matter) -> NodeRole:
"""Authorize managing this matter's ethical walls.
Checked against the matter's PARENT container, not the matter itself. A wall denies its
subject every role on the matter node — including manager — so authorizing wall management
there would let anyone lock themselves out permanently, with no way back short of a DBA.
A barrier is administered from outside it: you need `manager` on the department the matter
sits in. That also reads correctly as a rule — putting up a wall is a supervisory act."""
node = node_of(db, matter)
parent = db.get(Node, node.parent_id) if node.parent_id else None
if parent is None:
if not user.is_admin:
raise AuthorizationError("Chińskim murem zarządza administrator instancji.")
return NodeRole.manager
return authz.assert_role(db, user, parent, NodeRole.manager)
def open_matter(
db: DbSession,
user: AppUser,
*,
name: str,
client_party_id: uuid.UUID,
parent_node_id: uuid.UUID,
conflict_check_id: uuid.UUID,
token: str | None = None,
**fields,
) -> tuple[Matter, str | None]:
"""Open a matter. Returns (matter, case_file_warning)."""
name = (name or "").strip()
if not name:
raise ValidationError("Nazwa sprawy jest wymagana.")
client = db.get(Party, client_party_id)
if client is None:
raise ValidationError("Wskaż klienta.")
parent = nodes_svc.get_node(db, parent_node_id)
if parent.kind in nodes_svc.LEAF_KINDS:
raise ConflictError("Nie można założyć sprawy wewnątrz innej sprawy.")
authz.assert_role(db, user, parent, NodeRole.editor)
check = db.get(ConflictCheck, conflict_check_id)
if check is None:
raise ValidationError("Najpierw wykonaj sprawdzenie konfliktu interesów.")
if check.outcome == ConflictOutcome.pending:
raise ConflictError(
"Sprawdzenie konfliktu interesów czeka na rozstrzygnięcie — sprawy nie można otworzyć."
)
if check.outcome == ConflictOutcome.declined:
raise ConflictError("Zlecenie zostało odrzucone w sprawdzeniu konfliktu interesów.")
if check.matter_id is not None:
raise ConflictError(
"To sprawdzenie zostało już wykorzystane do otwarcia sprawy. Uruchom nowe."
)
node = nodes_svc.create_node(db, user, parent=parent, kind=NodeKind.matter, name=name)
matter = Matter(
node_id=node.id,
reference=next_reference(db),
name=name,
client_party_id=client.id,
status=MatterStatus.open,
responsible_lawyer_id=fields.pop("responsible_lawyer_id", None) or user.id,
originating_lawyer_id=fields.pop("originating_lawyer_id", None) or user.id,
opened_at=fields.pop("opened_at", None) or dt.date.today(),
**{k: v for k, v in fields.items() if v is not None},
)
db.add(matter)
db.flush()
db.add(MatterParty(matter_id=matter.id, party_id=client.id,
role=PartyRole.client, is_adverse=False))
check.matter_id = matter.id
db.flush()
node_id, warning = galena.try_create_case_file(
token, name=f"{matter.reference} {matter.name}"
)
if node_id:
matter.document_node_id = node_id
db.flush()
return matter, warning
def attach_case_file(db: DbSession, matter: Matter, token: str | None) -> str | None:
"""Retry case-file creation for a matter that has none. Returns a warning, or None on success."""
if matter.document_node_id:
raise ConflictError("Ta sprawa ma już akta.")
if not galena.enabled():
raise ConflictError("Integracja z Galeną nie jest skonfigurowana.")
node_id, warning = galena.try_create_case_file(
token, name=f"{matter.reference} {matter.name}"
)
if node_id:
matter.document_node_id = node_id
db.flush()
return None
return warning or "Nie udało się utworzyć akt sprawy."
# Fields a user can deliberately blank out. Everywhere else `None` means "not supplied" and is
# skipped — without this list there would be no way to REMOVE a rate override or unpin a card
# once set, which is the sort of one-way door that quietly bills a client at the wrong rate for
# a year. `name` and `status` are absent on purpose: nulling them is always a bug.
CLEARABLE_FIELDS = frozenset({
"description", "practice_area", "default_rate_minor", "rate_card_id", "fee_cap_minor",
"value_in_dispute", "court", "court_department", "case_signature", "instance",
"responsible_lawyer_id", "originating_lawyer_id",
})
def update_matter(db: DbSession, matter: Matter, **fields) -> Matter:
for key, value in fields.items():
if not hasattr(matter, key):
continue
if value is None and key not in CLEARABLE_FIELDS:
continue
setattr(matter, key, value)
if fields.get("status") == MatterStatus.closed and matter.closed_at is None:
matter.closed_at = dt.date.today()
db.flush()
return matter
def list_matters(
db: DbSession,
user: AppUser,
*,
q: str = "",
status: MatterStatus | None = None,
mine: bool = False,
limit: int = 200,
) -> list[Matter]:
"""Matters the user can read. Access is filtered in one batch, not per row."""
stmt = select(Matter)
if status is not None:
stmt = stmt.where(Matter.status == status)
if mine:
stmt = stmt.where(Matter.responsible_lawyer_id == user.id)
if q.strip():
like = f"%{q.strip()}%"
stmt = stmt.where(
or_(Matter.name.ilike(like), Matter.reference.ilike(like),
Matter.case_signature.ilike(like))
)
found = list(db.scalars(stmt.order_by(Matter.reference.desc()).limit(limit)).all())
if not found:
return []
node_by_id = {
n.id: n for n in
db.scalars(select(Node).where(Node.id.in_([m.node_id for m in found]))).all()
}
readable = authz.readable_node_ids(db, user, list(node_by_id.values()))
return [m for m in found if m.node_id in readable]
# ── parties on a matter ───────────────────────────────────────────────────────
def matter_parties(db: DbSession, matter: Matter) -> list[tuple[MatterParty, Party]]:
return list(
db.execute(
select(MatterParty, Party)
.join(Party, Party.id == MatterParty.party_id)
.where(MatterParty.matter_id == matter.id)
.order_by(MatterParty.role)
).all()
)
def add_party(db: DbSession, matter: Matter, party: Party, role: PartyRole,
note: str | None = None) -> MatterParty:
existing = db.scalar(
select(MatterParty).where(
MatterParty.matter_id == matter.id,
MatterParty.party_id == party.id,
MatterParty.role == role,
)
)
if existing:
return existing
row = MatterParty(matter_id=matter.id, party_id=party.id, role=role,
is_adverse=role in ADVERSE_ROLES, note=note)
db.add(row)
db.flush()
return row
def remove_party(db: DbSession, matter: Matter, matter_party_id: uuid.UUID) -> None:
row = db.get(MatterParty, matter_party_id)
if row is None or row.matter_id != matter.id:
raise NotFoundError("Nie znaleziono strony w tej sprawie.")
if row.role == PartyRole.client:
raise ConflictError("Klienta nie można usunąć ze sprawy.")
db.delete(row)
# ── ethical walls ─────────────────────────────────────────────────────────────
def walls(db: DbSession, matter: Matter) -> list[tuple[EthicalWall, AppUser]]:
return list(
db.execute(
select(EthicalWall, AppUser)
.join(AppUser, AppUser.id == EthicalWall.user_id)
.where(EthicalWall.matter_id == matter.id)
).all()
)
def set_wall(db: DbSession, matter: Matter, actor: AppUser, *, user_id: uuid.UUID,
mode, reason: str | None) -> EthicalWall:
target = db.get(AppUser, user_id)
if target is None:
raise NotFoundError("Nie znaleziono użytkownika.")
existing = db.scalar(
select(EthicalWall).where(
EthicalWall.matter_id == matter.id, EthicalWall.user_id == user_id
)
)
if existing:
existing.mode = mode
existing.reason = reason
db.flush()
return existing
row = EthicalWall(matter_id=matter.id, user_id=user_id, mode=mode,
reason=reason, created_by=actor.id)
db.add(row)
db.flush()
return row
def clear_wall(db: DbSession, matter: Matter, user_id: uuid.UUID) -> bool:
row = db.scalar(
select(EthicalWall).where(
EthicalWall.matter_id == matter.id, EthicalWall.user_id == user_id
)
)
if row is None:
return False
db.delete(row)
return True
+248
View File
@@ -0,0 +1,248 @@
"""Node-tree CRUD: firm → departments/teams → matters.
Copied from Galena (see SHARED.md) and adapted: `matter` is Sygna's leaf kind, so it takes the
place of Galena's `project` in every leaf rule. Sygna never creates a node of kind `project` —
those live in Galena's tree and are referenced by id from `matter.document_node_id`.
"""
from __future__ import annotations
import re
import uuid
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import NodeKind, PrincipalType
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, AuditLog, Favorite, Node, PermissionGrant
# Leaf kinds: nothing may be created inside one.
LEAF_KINDS = (NodeKind.matter, NodeKind.project)
_SLUG_RE = re.compile(r"[^a-z0-9]+")
# Latin-1 folding for slugs. Polish names are the normal case here, not the exception.
_PL_FOLD = str.maketrans({
"ą": "a", "ć": "c", "ę": "e", "ł": "l", "ń": "n", "ó": "o", "ś": "s", "ź": "z", "ż": "z",
"Ą": "a", "Ć": "c", "Ę": "e", "Ł": "l", "Ń": "n", "Ó": "o", "Ś": "s", "Ź": "z", "Ż": "z",
})
def slugify(name: str) -> str:
s = _SLUG_RE.sub("-", name.strip().lower().translate(_PL_FOLD)).strip("-")
return s or "item"
def unique_slug(db: DbSession, parent_id: uuid.UUID | None, base: str) -> str:
slug, i = base, 1
while db.scalar(
select(Node.id).where(Node.parent_id.is_(parent_id) if parent_id is None
else Node.parent_id == parent_id, Node.slug == slug)
):
i += 1
slug = f"{base}-{i}"
return slug
def get_node(db: DbSession, node_id: uuid.UUID) -> Node:
node = db.get(Node, node_id)
if node is None:
raise NotFoundError("Not found.")
return node
def all_nodes(db: DbSession) -> list[Node]:
"""Every node, ordered by path — the admin access picker."""
return list(db.scalars(select(Node).order_by(Node.path)).all())
def containers(db: DbSession) -> list[Node]:
"""Nodes a matter can be created under."""
return list(
db.scalars(
select(Node).where(Node.kind.notin_(LEAF_KINDS)).order_by(Node.path)
).all()
)
def _child_path(parent: Node | None, slug: str) -> str:
return f"/{slug}" if parent is None else f"{parent.path}/{slug}"
def create_node(
db: DbSession,
user: AppUser,
*,
parent: Node | None,
kind: NodeKind,
name: str,
personal_owner_id: uuid.UUID | None = None,
) -> Node:
"""Create a container or a matter node. Top-level must be a workspace; a matter is a leaf.
Matter nodes are created by services/matters.py, never directly by the nodes router — a
matter node without its `matter` row would be an orphan the authz resolver can't wall."""
name = (name or "").strip()
if not name:
raise ValidationError("A name is required.")
if parent is None and kind != NodeKind.workspace:
raise ValidationError("Top-level items must be workspaces.")
if parent is not None and parent.kind in LEAF_KINDS:
raise ConflictError("A matter is a leaf — nothing can be created inside it.")
if kind == NodeKind.project:
raise ConflictError(
"Projects live in Galena, not here. A matter's case file is created for it."
)
slug = unique_slug(db, parent.id if parent else None, slugify(name))
node = Node(
parent_id=parent.id if parent else None,
kind=kind,
name=name,
slug=slug,
path=_child_path(parent, slug),
owner_id=user.id,
personal_owner_id=personal_owner_id,
)
db.add(node)
db.flush()
return node
def children(db: DbSession, parent: Node | None) -> list[Node]:
stmt = select(Node).where(
Node.parent_id.is_(None) if parent is None else Node.parent_id == parent.id
).order_by(Node.kind, Node.name)
return list(db.scalars(stmt).all())
def breadcrumb(db: DbSession, node: Node) -> list[Node]:
from .authz import ancestor_paths
paths = ancestor_paths(node.path)
by_path = {n.path: n for n in db.scalars(select(Node).where(Node.path.in_(paths))).all()}
return [by_path[p] for p in paths if p in by_path]
def rename(db: DbSession, node: Node, new_name: str) -> Node:
new_name = (new_name or "").strip()
if not new_name:
raise ValidationError("A name is required.")
new_slug = unique_slug(db, node.parent_id, slugify(new_name))
_reslug(db, node, node.parent_id, new_slug)
node.name = new_name
db.flush()
return node
def move(db: DbSession, node: Node, new_parent: Node | None) -> Node:
if new_parent is not None:
if new_parent.kind in LEAF_KINDS:
raise ConflictError("Can't move into a matter.")
# Prevent moving a node into its own descendant.
if new_parent.path == node.path or new_parent.path.startswith(node.path + "/"):
raise ConflictError("Can't move an item into itself.")
if node.kind == NodeKind.workspace:
raise ConflictError("Workspaces are top-level and can't be moved into another item.")
new_slug = unique_slug(db, new_parent.id if new_parent else None, node.slug)
node.parent_id = new_parent.id if new_parent else None
_reslug(db, node, node.parent_id, new_slug)
db.flush()
return node
def _reslug(db: DbSession, node: Node, parent_id: uuid.UUID | None, new_slug: str) -> None:
"""Set node.slug=new_slug and rewrite the materialized path of node + all descendants."""
parent = db.get(Node, parent_id) if parent_id else None
old_path = node.path
new_path = _child_path(parent, new_slug)
if old_path == new_path and node.slug == new_slug:
return
descendants = list(
db.scalars(select(Node).where(Node.path.like(old_path + "/%"))).all()
)
node.slug = new_slug
node.path = new_path
for d in descendants:
d.path = new_path + d.path[len(old_path):]
def delete(db: DbSession, node: Node) -> None:
db.delete(node) # ON DELETE CASCADE removes descendants, grants, favourites, the matter
# ── scopes ────────────────────────────────────────────────────────────────────
def personal_workspace(db: DbSession, user: AppUser) -> Node:
node = db.scalar(select(Node).where(Node.personal_owner_id == user.id))
if node is None:
node = create_node(db, user, parent=None, kind=NodeKind.workspace,
name="Moje sprawy", personal_owner_id=user.id)
return node
def favorite_ids(db: DbSession, user: AppUser) -> set:
return set(db.scalars(select(Favorite.node_id).where(Favorite.user_id == user.id)).all())
def toggle_favorite(db: DbSession, user: AppUser, node: Node) -> bool:
"""Add/remove a favourite; returns the new favourited state."""
existing = db.get(Favorite, {"user_id": user.id, "node_id": node.id})
if existing:
db.delete(existing)
return False
db.add(Favorite(user_id=user.id, node_id=node.id))
return True
def accessible_workspaces(db: DbSession, user: AppUser) -> list[Node]:
"""Non-personal workspaces the user can read — the sidebar list."""
from . import authz
return [w for w in db.scalars(select(Node).where(Node.kind == NodeKind.workspace)).all()
if w.personal_owner_id is None and authz.effective_role(db, user, w) is not None]
def favorites(db: DbSession, user: AppUser) -> list[Node]:
from . import authz
ids = db.scalars(select(Favorite.node_id).where(Favorite.user_id == user.id)).all()
if not ids:
return []
found = db.scalars(select(Node).where(Node.id.in_(ids))).all()
return [n for n in found if authz.effective_role(db, user, n) is not None]
def shared_with_me(db: DbSession, user: AppUser) -> list[Node]:
"""Nodes with a direct grant to the user that aren't in their personal workspace."""
node_ids = db.scalars(
select(PermissionGrant.node_id).where(
PermissionGrant.principal_type == PrincipalType.user,
PermissionGrant.principal_id == user.id,
)
).all()
if not node_ids:
return []
found = db.scalars(select(Node).where(Node.id.in_(node_ids))).all()
personal = db.scalar(select(Node).where(Node.personal_owner_id == user.id))
ppath = personal.path if personal else None
return [n for n in found if not (ppath and n.path.startswith(ppath))]
def recent(db: DbSession, user: AppUser, limit: int = 20) -> list[AuditLog]:
"""The user's own actions + activity on nodes they can read — never the global audit log."""
from . import authz
rows = db.scalars(select(AuditLog).order_by(AuditLog.created_at.desc()).limit(300)).all()
node_ids = {r.entity_id for r in rows if r.entity_id and r.actor_id != user.id}
nodes_by_id = ({n.id: n for n in db.scalars(select(Node).where(Node.id.in_(node_ids))).all()}
if node_ids else {})
readable: dict = {}
def _readable(nid):
if nid not in readable:
n = nodes_by_id.get(nid)
readable[nid] = n is not None and authz.effective_role(db, user, n) is not None
return readable[nid]
out: list[AuditLog] = []
for r in rows:
if len(out) >= limit:
break
if r.actor_id == user.id or (r.entity_id and _readable(r.entity_id)):
out.append(r)
return out
+108
View File
@@ -0,0 +1,108 @@
"""In-app notifications: writing them, reading them, and not repeating them.
`push()` is idempotent on `(recipient, dedupe_key)`. That is the whole reason the scheduler can
run as often as it likes: it re-derives the same set of milestones every morning and only the
ones nobody has been told about actually become notifications.
"""
from __future__ import annotations
import datetime as dt
import logging
import uuid
from sqlalchemy import select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session as DbSession
from ..enums import NotificationKind
from ..models import AppUser, Notification, NotificationPref
log = logging.getLogger("sygna.notify")
def prefs_for(db: DbSession, user_id: uuid.UUID) -> NotificationPref:
row = db.get(NotificationPref, user_id)
if row is None:
row = NotificationPref(user_id=user_id)
db.add(row)
db.flush()
return row
def set_prefs(db: DbSession, user_id: uuid.UUID, **fields) -> NotificationPref:
row = prefs_for(db, user_id)
for key, value in fields.items():
if value is not None and hasattr(row, key):
setattr(row, key, value)
db.flush()
return row
def push(
db: DbSession,
recipient_id: uuid.UUID,
*,
kind: NotificationKind,
title: str,
body: str | None = None,
link: str | None = None,
payload: dict | None = None,
dedupe_key: str | None = None,
) -> Notification | None:
"""Create one notification. Returns None when it was a duplicate or the user opted out.
The uniqueness check is a real constraint, not a SELECT-then-INSERT: two schedulers (or a
scheduler and a hand-triggered run) must not both slip a reminder through the gap."""
if not prefs_for(db, recipient_id).inapp:
return None
row = Notification(recipient_id=recipient_id, kind=kind, title=title, body=body,
link=link, payload=payload, dedupe_key=dedupe_key)
savepoint = db.begin_nested()
try:
db.add(row)
savepoint.commit()
except IntegrityError:
savepoint.rollback()
return None
return row
def unread_count(db: DbSession, user_id: uuid.UUID) -> int:
return len(
db.scalars(
select(Notification.id).where(
Notification.recipient_id == user_id, Notification.read_at.is_(None)
)
).all()
)
def listing(db: DbSession, user_id: uuid.UUID, *, limit: int = 50,
unread_only: bool = False) -> list[Notification]:
stmt = select(Notification).where(Notification.recipient_id == user_id)
if unread_only:
stmt = stmt.where(Notification.read_at.is_(None))
return list(db.scalars(stmt.order_by(Notification.created_at.desc()).limit(limit)).all())
def mark_read(db: DbSession, user_id: uuid.UUID, notification_id: uuid.UUID) -> bool:
row = db.get(Notification, notification_id)
if row is None or row.recipient_id != user_id:
return False
if row.read_at is None:
row.read_at = dt.datetime.now(dt.timezone.utc)
return True
def mark_all_read(db: DbSession, user_id: uuid.UUID) -> int:
result = db.execute(
update(Notification)
.where(Notification.recipient_id == user_id, Notification.read_at.is_(None))
.values(read_at=dt.datetime.now(dt.timezone.utc))
)
return result.rowcount or 0
def admins(db: DbSession) -> list[AppUser]:
return list(db.scalars(select(AppUser).where(AppUser.is_admin.is_(True),
AppUser.is_active.is_(True))).all())
+227
View File
@@ -0,0 +1,227 @@
"""Parties: CRUD plus the name normalisation the conflict engine matches on.
Polish names are the normal case here, so normalisation has to handle two things an
English-language product gets wrong:
1. **Diacritics.** "Łódź" and "Lodz" are the same client. Folded on the way in.
2. **Declension.** "Kowalski", "Kowalskiego", "Kowalskiemu" are the same person; "Nowakiem"
and "Nowak" likewise. `_stem()` below strips the common inflectional endings. It is a
deliberate approximation — crude, and it over-stems short words — but a conflict check is
allowed to over-match: a false positive costs a lawyer thirty seconds, a false negative
costs the firm a disciplinary case. Replacing `_stem()` with Morfologik (BSD) is the
documented upgrade path; nothing else depends on how it works.
"""
from __future__ import annotations
import re
import uuid
from sqlalchemy import or_, select
from sqlalchemy.orm import Session as DbSession
from ..enums import PartyKind
from ..errors import NotFoundError, ValidationError
from ..models import AppUser, Party, PartyAlias, PartyLink
_FOLD = str.maketrans({
"ą": "a", "ć": "c", "ę": "e", "ł": "l", "ń": "n", "ó": "o", "ś": "s", "ź": "z", "ż": "z",
"Ą": "a", "Ć": "c", "Ę": "e", "Ł": "l", "Ń": "n", "Ó": "o", "Ś": "s", "Ź": "z", "Ż": "z",
})
# Legal forms carry no identifying information — "Kowalski sp. z o.o." and "Kowalski S.A."
# must both reduce to "kowalski" or the conflict engine misses the group.
_LEGAL_FORMS = (
"spolka z ograniczona odpowiedzialnoscia",
"spolka akcyjna", "spolka komandytowo akcyjna", "spolka komandytowa",
"spolka jawna", "spolka partnerska", "spolka cywilna",
"prosta spolka akcyjna",
"sp z o o", "sp z oo", "spzoo", "s a", "sa", "sp j", "sp k", "s k a", "sp p", "p s a",
"spolka", "przedsiebiorstwo", "fundacja", "stowarzyszenie", "kancelaria",
"w organizacji", "w likwidacji", "w upadlosci",
)
_PUNCT = re.compile(r"[^a-z0-9]+")
# Ordered longest-first, so "Kowalskiego" loses "-iego" (→ kowalsk) rather than just "-o",
# and lands on the same stem as "Kowalski" (→ kowalsk). Diacritics are already folded by the
# time _stem runs, so these are all ASCII.
_ENDINGS = ("iego", "iemu", "owie", "ego", "emu", "ich", "ych", "imi", "ymi", "ami", "ach",
"owi", "iem", "ie", "ia", "ii", "ow", "om", "im", "ym", "em",
"a", "e", "i", "o", "u", "y")
def _fold(s: str) -> str:
return _PUNCT.sub(" ", (s or "").translate(_FOLD).lower()).strip()
def normalize(name: str) -> str:
"""The stored `search_key`: folded, punctuation-stripped, legal forms removed."""
s = _fold(name)
for form in _LEGAL_FORMS:
s = re.sub(rf"(?:^|\s){re.escape(form)}(?:\s|$)", " ", s)
return re.sub(r"\s+", " ", s).strip()
def _stem(token: str) -> str:
"""Approximate Polish stem: strip one inflectional ending, keep at least 4 characters."""
for end in _ENDINGS:
if len(token) - len(end) >= 4 and token.endswith(end):
return token[: -len(end)]
return token
def stems(name: str) -> set[str]:
"""The comparison key set for fuzzy matching. Tokens shorter than 3 characters are dropped
— they are initials and prepositions, and matching on them produces noise."""
return {_stem(t) for t in normalize(name).split() if len(t) >= 3}
def similarity(a: str, b: str) -> float:
"""Containment score in [0, 1]: how much of the smaller name appears in the larger one.
Containment rather than Jaccard, deliberately — "Kowalski" must score 1.0 against
"Kowalski Nowak i Wspólnicy", because acting against one partner of a firm we act for is
exactly the conflict we are looking for."""
sa, sb = stems(a), stems(b)
if not sa or not sb:
return 0.0
return len(sa & sb) / min(len(sa), len(sb))
# ── CRUD ──────────────────────────────────────────────────────────────────────
def get_party(db: DbSession, party_id: uuid.UUID) -> Party:
party = db.get(Party, party_id)
if party is None:
raise NotFoundError("Nie znaleziono strony.")
return party
def list_parties(db: DbSession, q: str = "", limit: int = 100) -> list[Party]:
stmt = select(Party).order_by(Party.name).limit(limit)
if q.strip():
key = f"%{normalize(q)}%"
like = f"%{q.strip()}%"
stmt = select(Party).where(
or_(Party.search_key.like(key), Party.name.ilike(like),
Party.nip == q.strip(), Party.krs == q.strip())
).order_by(Party.name).limit(limit)
return list(db.scalars(stmt).all())
def create_party(db: DbSession, user: AppUser, *, kind: PartyKind, name: str, **fields) -> Party:
name = (name or "").strip()
if not name:
raise ValidationError("Nazwa jest wymagana.")
party = Party(
kind=kind,
name=name,
search_key=normalize(name),
created_by=user.id,
**{k: v for k, v in fields.items() if v is not None},
)
db.add(party)
db.flush()
return party
def update_party(db: DbSession, party: Party, **fields) -> Party:
for key, value in fields.items():
if value is not None and hasattr(party, key):
setattr(party, key, value)
if "name" in fields and fields["name"]:
party.search_key = normalize(party.name)
db.flush()
return party
def add_alias(db: DbSession, party: Party, alias: str) -> PartyAlias:
alias = (alias or "").strip()
if not alias:
raise ValidationError("Alias nie może być pusty.")
key = normalize(alias)
existing = db.scalar(
select(PartyAlias).where(PartyAlias.party_id == party.id, PartyAlias.search_key == key)
)
if existing:
return existing
row = PartyAlias(party_id=party.id, alias=alias, search_key=key)
db.add(row)
db.flush()
return row
def link(db: DbSession, from_party: Party, to_party: Party, relation, note: str | None = None):
if from_party.id == to_party.id:
raise ValidationError("Nie można powiązać strony z samą sobą.")
existing = db.scalar(
select(PartyLink).where(
PartyLink.from_party_id == from_party.id,
PartyLink.to_party_id == to_party.id,
PartyLink.relation == relation,
)
)
if existing:
return existing
row = PartyLink(from_party_id=from_party.id, to_party_id=to_party.id,
relation=relation, note=note)
db.add(row)
db.flush()
return row
def by_ids(db: DbSession, ids) -> dict[uuid.UUID, Party]:
"""Batch load for list screens — one query, not one per row."""
ids = set(ids)
if not ids:
return {}
return {p.id: p for p in db.scalars(select(Party).where(Party.id.in_(ids))).all()}
def aliases_for(db: DbSession, party: Party) -> list[PartyAlias]:
return list(
db.scalars(
select(PartyAlias).where(PartyAlias.party_id == party.id).order_by(PartyAlias.alias)
).all()
)
def links_for(db: DbSession, party: Party) -> list[tuple[PartyLink, Party]]:
"""Links in both directions, presented from this party's point of view."""
rows = list(
db.scalars(
select(PartyLink).where(
or_(PartyLink.from_party_id == party.id, PartyLink.to_party_id == party.id)
)
).all()
)
if not rows:
return []
other_ids = {
(row.to_party_id if row.from_party_id == party.id else row.from_party_id) for row in rows
}
others = {p.id: p for p in db.scalars(select(Party).where(Party.id.in_(other_ids))).all()}
out = []
for row in rows:
other_id = row.to_party_id if row.from_party_id == party.id else row.from_party_id
other = others.get(other_id)
if other is not None:
out.append((row, other))
return out
def related_party_ids(db: DbSession, party_ids: set[uuid.UUID]) -> set[uuid.UUID]:
"""One hop out along party_link, in both directions. One hop, not transitive closure:
a client's parent company is a conflict; its parent's unrelated other subsidiary is a
judgement call the lawyer makes, and burying it in a hundred hits helps nobody."""
if not party_ids:
return set()
rows = db.execute(
select(PartyLink.from_party_id, PartyLink.to_party_id).where(
or_(PartyLink.from_party_id.in_(party_ids), PartyLink.to_party_id.in_(party_ids))
)
).all()
out: set[uuid.UUID] = set()
for a, b in rows:
out.add(a)
out.add(b)
return out - party_ids
+305
View File
@@ -0,0 +1,305 @@
"""Rate resolution: which hourly rate applies to this person, on this matter, on this date.
`resolve()` returns the rate **and where it came from**. That second half is not decoration: the
first question anyone asks about an invoice line is "why 520 and not 450", and a system that
cannot answer it turns every billing query into an archaeology exercise.
Scopes, most specific first:
1. `matter.default_rate_minor` — a flat override typed on the matter. Beats everything.
2. the card pinned to the matter (`matter.rate_card_id`)
3. the client's card
4. the firm's default card
5. `app_setting.default_rate_minor` — the house rate of last resort
Within a card, the same idea: this person → this grade → the card's fallback.
Cards are effective-dated, and resolution takes the date of the WORK, not today. Recording last
month's time next Tuesday must price it at last month's rate.
"""
from __future__ import annotations
import dataclasses
import datetime as dt
import uuid
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import Seniority
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, LawyerProfile, Matter, RateCard, RateCardEntry
from . import settings as settings_svc
# The resolver composes a sentence a lawyer reads, and every other user-facing string the server
# emits is already Polish — so the grade is too, rather than leaking `senior_associate` into the
# middle of one.
SENIORITY_PL = {
Seniority.partner: "partner",
Seniority.counsel: "counsel",
Seniority.senior_associate: "starszy prawnik",
Seniority.associate: "prawnik",
Seniority.trainee: "aplikant",
Seniority.paralegal: "asystent",
Seniority.other: "inny",
}
@dataclasses.dataclass(frozen=True)
class ResolvedRate:
rate_minor: int | None
source: str # machine-readable: matter_override | matter_card | client_card | …
label: str # what the console shows a human
card_id: uuid.UUID | None = None
def as_dict(self) -> dict:
return {"rate_minor": self.rate_minor, "source": self.source, "label": self.label,
"card_id": str(self.card_id) if self.card_id else None}
# ── profiles ──────────────────────────────────────────────────────────────────
def profile_for(db: DbSession, user_id: uuid.UUID) -> LawyerProfile | None:
return db.scalar(select(LawyerProfile).where(LawyerProfile.user_id == user_id))
def upsert_profile(db: DbSession, user_id: uuid.UUID, **fields) -> LawyerProfile:
if db.get(AppUser, user_id) is None:
raise NotFoundError("Nie znaleziono użytkownika.")
row = profile_for(db, user_id)
if row is None:
row = LawyerProfile(user_id=user_id)
db.add(row)
for key, value in fields.items():
if value is not None and hasattr(row, key):
setattr(row, key, value)
db.flush()
return row
def profiles(db: DbSession) -> dict:
return {p.user_id: p for p in db.scalars(select(LawyerProfile)).all()}
# ── cards ─────────────────────────────────────────────────────────────────────
def get_card(db: DbSession, card_id: uuid.UUID) -> RateCard:
card = db.get(RateCard, card_id)
if card is None:
raise NotFoundError("Nie znaleziono cennika.")
return card
def list_cards(db: DbSession) -> list[RateCard]:
return list(
db.scalars(
select(RateCard).order_by(RateCard.is_default.desc(), RateCard.valid_from.desc(),
RateCard.name)
).all()
)
def create_card(db: DbSession, user: AppUser, *, name: str, valid_from: dt.date,
client_party_id: uuid.UUID | None = None, is_default: bool = False,
**fields) -> RateCard:
name = (name or "").strip()
if not name:
raise ValidationError("Nazwa cennika jest wymagana.")
if valid_from is None:
raise ValidationError("Podaj datę obowiązywania od.")
if is_default and client_party_id is not None:
raise ValidationError("Cennik domyślny kancelarii nie może być przypisany do klienta.")
card = RateCard(
name=name, valid_from=valid_from, client_party_id=client_party_id,
is_default=is_default, created_by_id=user.id,
**{k: v for k, v in fields.items() if v is not None},
)
db.add(card)
db.flush()
if is_default:
_demote_other_defaults(db, card)
return card
def update_card(db: DbSession, card: RateCard, **fields) -> RateCard:
for key, value in fields.items():
if value is not None and hasattr(card, key):
setattr(card, key, value)
if card.valid_to and card.valid_to < card.valid_from:
raise ValidationError("Data „obowiązuje do” nie może być wcześniejsza niż „od”.")
db.flush()
if card.is_default:
if card.client_party_id is not None:
raise ValidationError(
"Cennik domyślny kancelarii nie może być przypisany do klienta."
)
_demote_other_defaults(db, card)
return card
def _demote_other_defaults(db: DbSession, keep: RateCard) -> None:
"""Exactly one house card. Swapping is a two-step edit, so this is done in the service
rather than by a constraint that would reject the intermediate state."""
for other in db.scalars(
select(RateCard).where(RateCard.is_default.is_(True), RateCard.id != keep.id)
).all():
other.is_default = False
db.flush()
def delete_card(db: DbSession, card: RateCard) -> None:
pinned = db.scalar(select(Matter.id).where(Matter.rate_card_id == card.id).limit(1))
if pinned:
raise ConflictError(
"Ten cennik jest przypisany do spraw. Odepnij go najpierw albo ustaw datę końca "
"obowiązywania — usunięcie zostawiłoby sprawy bez stawki."
)
db.delete(card)
def entries(db: DbSession, card: RateCard) -> list[RateCardEntry]:
return list(
db.scalars(
select(RateCardEntry).where(RateCardEntry.rate_card_id == card.id)
.order_by(RateCardEntry.rate_minor.desc())
).all()
)
def set_entry(db: DbSession, card: RateCard, *, rate_minor: int,
user_id: uuid.UUID | None = None, seniority: Seniority | None = None,
note: str | None = None) -> RateCardEntry:
if user_id and seniority:
raise ValidationError("Stawka dotyczy albo osoby, albo stopnia — nie obu naraz.")
if not rate_minor or int(rate_minor) <= 0:
raise ValidationError("Stawka musi być dodatnia.")
existing = db.scalar(
select(RateCardEntry).where(
RateCardEntry.rate_card_id == card.id,
RateCardEntry.user_id == user_id if user_id else RateCardEntry.user_id.is_(None),
RateCardEntry.seniority == seniority if seniority
else RateCardEntry.seniority.is_(None),
)
)
if existing:
existing.rate_minor = int(rate_minor)
existing.note = note
db.flush()
return existing
row = RateCardEntry(rate_card_id=card.id, user_id=user_id, seniority=seniority,
rate_minor=int(rate_minor), note=note)
db.add(row)
db.flush()
return row
def delete_entry(db: DbSession, card: RateCard, entry_id: uuid.UUID) -> None:
row = db.get(RateCardEntry, entry_id)
if row is None or row.rate_card_id != card.id:
raise NotFoundError("Nie znaleziono stawki.")
db.delete(row)
# ── resolution ────────────────────────────────────────────────────────────────
def _effective(cards: list[RateCard], on_date: dt.date) -> RateCard | None:
"""The card in force on `on_date`. If several qualify, the one that started most recently —
a card issued later supersedes an older open-ended one."""
live = [
c for c in cards
if c.valid_from <= on_date and (c.valid_to is None or on_date <= c.valid_to)
]
if not live:
return None
return max(live, key=lambda c: c.valid_from)
def _entry_for(db: DbSession, card: RateCard, user_id: uuid.UUID,
seniority: Seniority | None) -> tuple[RateCardEntry | None, str]:
"""This person → this grade → the card's fallback."""
rows = entries(db, card)
for row in rows:
if row.user_id == user_id:
return row, "osoba"
if seniority is not None:
for row in rows:
if row.seniority == seniority:
return row, f"stopień: {SENIORITY_PL.get(seniority, seniority.value)}"
for row in rows:
if row.user_id is None and row.seniority is None:
return row, "stawka podstawowa cennika"
return None, ""
def _client_cards(db: DbSession, client_party_id: uuid.UUID | None) -> list[RateCard]:
if client_party_id is None:
return []
return list(
db.scalars(select(RateCard).where(RateCard.client_party_id == client_party_id)).all()
)
def _default_cards(db: DbSession) -> list[RateCard]:
return list(
db.scalars(
select(RateCard).where(RateCard.is_default.is_(True),
RateCard.client_party_id.is_(None))
).all()
)
def resolve(db: DbSession, matter: Matter, user_id: uuid.UUID,
on_date: dt.date | None = None) -> ResolvedRate:
"""The rate for `user_id` on `matter` for work done on `on_date` (default: today)."""
on_date = on_date or dt.date.today()
if matter.default_rate_minor:
return ResolvedRate(int(matter.default_rate_minor), "matter_override",
"stawka ustalona na sprawie")
profile = profile_for(db, user_id)
seniority = profile.seniority if profile else None
if matter.rate_card_id:
card = db.get(RateCard, matter.rate_card_id)
if card is not None:
entry, how = _entry_for(db, card, user_id, seniority)
if entry:
return ResolvedRate(entry.rate_minor, "matter_card",
f"cennik sprawy „{card.name}” ({how})", card.id)
card = _effective(_client_cards(db, matter.client_party_id), on_date)
if card is not None:
entry, how = _entry_for(db, card, user_id, seniority)
if entry:
return ResolvedRate(entry.rate_minor, "client_card",
f"cennik klienta „{card.name}” ({how})", card.id)
card = _effective(_default_cards(db), on_date)
if card is not None:
entry, how = _entry_for(db, card, user_id, seniority)
if entry:
return ResolvedRate(entry.rate_minor, "firm_card",
f"cennik kancelarii „{card.name}” ({how})", card.id)
house = settings_svc.get_int(db, "default_rate_minor", 0)
if house > 0:
return ResolvedRate(house, "settings", "stawka domyślna kancelarii")
return ResolvedRate(None, "none", "brak stawki — ustal cennik lub stawkę na sprawie")
def preview(db: DbSession, matter: Matter, on_date: dt.date | None = None) -> list[dict]:
"""What every user would be billed at on this matter — the table the matter screen shows,
so a partner can see the whole picture before the first invoice, not after."""
on_date = on_date or dt.date.today()
profs = profiles(db)
out = []
for user in db.scalars(select(AppUser).where(AppUser.is_active.is_(True))
.order_by(AppUser.full_name)).all():
resolved = resolve(db, matter, user.id, on_date)
profile = profs.get(user.id)
out.append({
"user_id": str(user.id), "name": user.full_name,
"seniority": profile.seniority.value if profile else None,
**resolved.as_dict(),
})
return out
+213
View File
@@ -0,0 +1,213 @@
"""Public registers: mapping their payloads onto Sygna's party record.
Pure functions — the HTTP lives in `integrations/registers.py`. Splitting it that way means the
mapping is tested against a real captured response instead of against a live service that
changes underneath the test suite.
**What the KRS API actually gives you, and what it does not.**
The register's public JSON API returns the *entity* in full — name, legal form, NIP, REGON,
address, e-mail, website, and the e-Doręczenia (BAE) address — plus the representation rules.
It **masks the names of natural persons**: a board member comes back as `N**********` with a
PESEL of `7**********`. This was verified against three unrelated companies; it is policy, not
an artefact.
The consequence is worth stating plainly because it shapes the feature: **officers and
shareholders cannot be pulled into the conflict engine from this API.** Sygna records how many
there are and what their functions are, marks them as redacted, and asks a human to type the
names. Inventing a link from `N**********` would put a fake party in the register that decides
whether the firm may take a case, which is the last place to guess.
"""
from __future__ import annotations
import datetime as dt
import re
from ..errors import ValidationError
# A masked value from the register: one visible character then asterisks, or all asterisks.
_MASKED = re.compile(r"^\**$|^.\*{2,}$")
KRS_REGISTRIES = ("P", "S") # P = przedsiębiorcy, S = stowarzyszenia i inne
def is_masked(value: str | None) -> bool:
"""Whether the register redacted this value rather than returning it."""
if not value:
return False
return bool(_MASKED.match(value.strip()))
def clean_krs(value: str) -> str:
digits = re.sub(r"\D", "", value or "")
if len(digits) != 10:
raise ValidationError("Numer KRS ma 10 cyfr.")
return digits
def clean_nip(value: str) -> str:
digits = re.sub(r"\D", "", value or "")
if len(digits) != 10:
raise ValidationError("NIP ma 10 cyfr.")
return digits
def nip_checksum_ok(nip: str) -> bool:
"""The statutory NIP check digit. Catches a typo before it reaches a government API —
and before it ends up on an invoice."""
digits = re.sub(r"\D", "", nip or "")
if len(digits) != 10:
return False
weights = (6, 5, 7, 2, 3, 4, 5, 6, 7)
total = sum(int(d) * w for d, w in zip(digits[:9], weights))
return total % 11 == int(digits[9])
# Legal-form and grammatical particles keep their conventional casing, so we never produce
# "Sp. Z O.O.".
_PARTICLES = {
"z": "z", "i": "i", "w": "w", "oraz": "oraz", "sp.": "sp.", "o.o.": "o.o.",
"sp.j.": "sp.j.", "sp.k.": "sp.k.", "s.a.": "S.A.", "s.k.a.": "S.K.A.",
"p.s.a.": "P.S.A.", "sp.p.": "sp.p.",
}
_VOWELS = set("aeiouyąęó")
def _title_token(token: str) -> str:
low = token.lower()
if low in _PARTICLES:
return _PARTICLES[low]
letters = re.sub(r"[^a-ząćęłńóśźż]", "", low)
# An all-caps token with no vowels is an acronym, not a shouted word: CD, PKN, KGHM.
# Lower-casing those was producing "cd Projekt Red".
if token.isupper() and letters and not (set(letters) & _VOWELS) and len(letters) <= 5:
return token
# Capitalise after a hyphen too, or "SKŁODOWSKIEJ-CURIE" comes out as "Skłodowskiej-curie".
return "-".join(p[:1].upper() + p[1:] for p in low.split("-"))
def _title(value: str | None) -> str | None:
"""The register shouts everything in upper case; make it readable without mangling
acronyms or legal-form particles."""
if not value:
return None
return " ".join(_title_token(w) for w in value.strip().split())
def _address(adres: dict | None) -> str | None:
if not adres:
return None
street = " ".join(filter(None, [
_title(adres.get("ulica")),
adres.get("nrDomu"),
]))
if adres.get("nrLokalu"):
street = f"{street}/{adres['nrLokalu']}"
city = " ".join(filter(None, [adres.get("kodPocztowy"), _title(adres.get("miejscowosc"))]))
return ", ".join(filter(None, [street.strip(), city.strip()])) or None
def _person(entry: dict) -> dict:
surname = (entry.get("nazwisko") or {}).get("nazwiskoICzlon")
names = entry.get("imiona") or {}
given = " ".join(filter(None, [names.get("imie"), names.get("imieDrugie")]))
return {
"surname": surname,
"given_names": given or None,
"function": entry.get("funkcjaWOrganie") or entry.get("rodzajProkury"),
# True when the register redacted the name — the caller must not treat it as a party.
"redacted": is_masked(surname) or is_masked(names.get("imie")),
}
def normalize_krs(payload: dict) -> dict:
"""Map an OdpisAktualny response onto the fields Sygna stores."""
odpis = (payload or {}).get("odpis") or {}
dane = odpis.get("dane") or {}
d1 = dane.get("dzial1") or {}
d2 = dane.get("dzial2") or {}
subject = d1.get("danePodmiotu") or {}
seat = d1.get("siedzibaIAdres") or {}
ident = subject.get("identyfikatory") or {}
rep = d2.get("reprezentacja") or {}
officers = [_person(p) for p in (rep.get("sklad") or [])]
for organ in d2.get("organNadzoru") or []:
officers += [{**_person(p), "function": organ.get("nazwa") or "ORGAN NADZORU"}
for p in (organ.get("sklad") or [])]
officers += [_person(p) for p in (d2.get("prokurenci") or [])]
# REGON comes back zero-padded to 14 for some entities; the 9-digit form is the usual one.
regon = ident.get("regon")
if regon and len(regon) == 14 and regon.endswith("00000"):
regon = regon[:9]
return {
"source": "KRS",
"krs": (odpis.get("naglowekA") or {}).get("numerKRS"),
"as_of": (odpis.get("naglowekA") or {}).get("stanZDnia"),
"name": _title(subject.get("nazwa")),
"raw_name": subject.get("nazwa"),
"legal_form": _title(subject.get("formaPrawna")),
"nip": ident.get("nip"),
"regon": regon,
"address": _address(seat.get("adres")),
"email": (seat.get("adresPocztyElektronicznej") or "").lower() or None,
"website": (seat.get("adresStronyInternetowej") or "").lower() or None,
# Straight from the register — a genuine head start on Phase 2's e-Doręczenia work.
"edoreczenia_address": seat.get("adresDoDoreczenElektronicznychWpisanyDoBAE"),
"representation": rep.get("sposobReprezentacji"),
"officers": officers,
# The honest headline for the UI.
"officers_redacted": any(o["redacted"] for o in officers),
}
def normalize_vat(payload: dict) -> dict:
"""Map a Biała lista (wykaz podatników VAT) response."""
result = (payload or {}).get("result") or {}
subject = result.get("subject") or {}
if not subject:
return {"source": "Biała lista", "found": False,
"checked_on": dt.date.today().isoformat()}
return {
"source": "Biała lista",
"found": True,
"checked_on": dt.date.today().isoformat(),
"request_id": result.get("requestId"),
"name": _title(subject.get("name")),
"raw_name": subject.get("name"),
"nip": subject.get("nip"),
"regon": subject.get("regon"),
"krs": subject.get("krs"),
"vat_status": subject.get("statusVat"),
"vat_active": (subject.get("statusVat") or "").lower().startswith("czynny"),
"address": _title(subject.get("workingAddress") or subject.get("residenceAddress")),
# Verify a counterparty's account before a disbursement leaves the client account.
"account_numbers": subject.get("accountNumbers") or [],
# Populated for some entity types, empty for listed companies. Names here are NOT masked.
"representatives": subject.get("representatives") or [],
"partners": subject.get("partners") or [],
}
# Which party fields each register may fill. `search_key` is recomputed by services/parties.
KRS_FIELDS = ("name", "nip", "regon", "krs", "address", "email", "edoreczenia_address")
VAT_FIELDS = ("name", "nip", "regon", "krs", "address")
def party_updates(data: dict, party, *, overwrite: bool = False) -> dict:
"""The subset of register data that should be written to this party.
Defaults to filling blanks only. A register is authoritative about a company's registered
details, but the firm may have deliberately recorded a correspondence address or a trading
name — overwriting that silently would lose work someone did on purpose."""
fields = KRS_FIELDS if data.get("source") == "KRS" else VAT_FIELDS
updates = {}
for field in fields:
value = data.get(field)
if not value:
continue
if overwrite or not getattr(party, field, None):
updates[field] = value
return updates
+272
View File
@@ -0,0 +1,272 @@
"""The reminder engine: turning computed dates into somebody being told.
A deadline system that requires you to remember to look at it is not a deadline system. This is
the other half of the engine — it re-derives, every run, the set of things that need attention
and pushes a notification for each milestone exactly once.
Design decisions worth keeping:
- **Idempotent by construction.** Every reminder carries a `dedupe_key` naming the milestone
(`deadline:<id>:d7`), and `notify.push` enforces uniqueness with a real constraint. Running
the scheduler twice, or at 09:00 and again after a restart, changes nothing.
- **It escalates rather than nags.** Approaching deadlines are announced at fixed milestones;
an overdue one is announced once to its owner, and again three days later to the people who
manage the matter. Daily repetition trains people to ignore it.
- **Ethical walls apply.** A recipient who cannot read the matter is never told it exists —
the reminder goes through the same authz resolver as everything else, so a wall is not
quietly leaked by a notification.
"""
from __future__ import annotations
import datetime as dt
import logging
import uuid
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import (
ConflictOutcome,
CorrespondenceStatus,
DeadlineSource,
NodeRole,
NotificationKind,
)
from ..models import AppUser, ConflictCheck, Correspondence, Deadline, Matter, Node
from . import authz, correspondence as corr_svc, notify
log = logging.getLogger("sygna.reminders")
# Days before a deadline at which it is announced. Deliberately sparse — a reminder every day
# for a fortnight is noise, and noise is what gets a real warning missed.
MILESTONES = (14, 7, 3, 1, 0)
# Days after a missed deadline before it goes to whoever manages the matter.
ESCALATE_AFTER_DAYS = 3
# How long an item may sit unassigned in the inbox before someone is asked about it.
INBOX_STALE_DAYS = 2
# How long a conflict check may sit undecided. Short, because nothing can be opened until it is.
CONFLICT_STALE_DAYS = 1
# How many rows one reminder pass will scan per category. Generous, because the whole point is
# to reach the neglected tail; bounded, so one runaway table cannot stall the scheduler.
SCAN_LIMIT = 1000
def _readable_by(db: DbSession, node: Node, user_ids: set[uuid.UUID]) -> list[AppUser]:
"""Filter candidate recipients to those who may actually see this matter."""
if not user_ids:
return []
users = db.scalars(
select(AppUser).where(AppUser.id.in_(user_ids), AppUser.is_active.is_(True))
).all()
return [u for u in users if authz.effective_role(db, u, node) is not None]
def _deadline_link(matter_id) -> str:
return f"#/matters/{matter_id}?tab=deadlines"
def _due_phrase(days_left: int) -> str:
if days_left == 0:
return "upływa dziś"
if days_left == 1:
return "upływa jutro"
return f"upływa za {days_left} dni"
def _run_deadlines(db: DbSession, today: dt.date) -> int:
sent = 0
rows = db.execute(
select(Deadline, Matter, Node)
.join(Matter, Matter.id == Deadline.matter_id)
.join(Node, Node.id == Matter.node_id)
.where(Deadline.completed_at.is_(None))
).all()
for deadline, matter, node in rows:
days_left = (deadline.due_date - today).days
owners = {deadline.owner_id, matter.responsible_lawyer_id} - {None}
if days_left in MILESTONES:
for user in _readable_by(db, node, owners):
if notify.push(
db, user.id, kind=NotificationKind.deadline_due,
title=f"Termin {_due_phrase(days_left)}: {deadline.title}",
body=f"{matter.reference} {matter.name}"
+ (f" — {deadline.basis}" if deadline.basis else ""),
link=_deadline_link(matter.id),
dedupe_key=f"deadline:{deadline.id}:d{days_left}",
):
sent += 1
elif days_left < 0:
overdue = abs(days_left)
for user in _readable_by(db, node, owners):
if notify.push(
db, user.id, kind=NotificationKind.deadline_overdue,
title=f"TERMIN MINĄŁ: {deadline.title}",
body=f"{matter.reference} {matter.name} — minął {overdue} dni temu "
f"({deadline.due_date.isoformat()})",
link=_deadline_link(matter.id),
dedupe_key=f"deadline:{deadline.id}:overdue",
):
sent += 1
# Escalate once, to the people who manage the matter — not to everyone, and not
# every morning. In a firm where the owner IS the only manager (a solo practice,
# which is most of the market) there is nobody above them, so the escalation comes
# back to them as a second, louder notice rather than vanishing.
if overdue >= ESCALATE_AFTER_DAYS:
managers = authz.users_with_role_at_least(db, node, NodeRole.manager) - owners
recipients = _readable_by(db, node, managers) or _readable_by(db, node, owners)
for user in recipients:
if notify.push(
db, user.id, kind=NotificationKind.deadline_overdue,
title=f"Niedotrzymany termin bez reakcji: {deadline.title}",
body=f"{matter.reference} {matter.name} — minął {overdue} dni temu "
"i nadal nie został zamknięty.",
link=_deadline_link(matter.id),
dedupe_key=f"deadline:{deadline.id}:escalated",
):
sent += 1
# A statutory or court deadline nobody has confirmed is only half-managed. Ask the
# people who could confirm it — never the person who entered it, since dual control
# refuses them anyway and telling them would just be noise.
if (deadline.confirmed_at is None
and deadline.source in (DeadlineSource.statute, DeadlineSource.court)
and 0 <= days_left):
candidates = authz.users_with_role_at_least(db, node, NodeRole.editor)
candidates -= {deadline.created_by_id} - {None}
for user in _readable_by(db, node, candidates):
if notify.push(
db, user.id, kind=NotificationKind.deadline_unconfirmed,
title=f"Termin do potwierdzenia: {deadline.title}",
body=f"{matter.reference} {matter.name} — termin "
f"{deadline.source.value} wymaga potwierdzenia przez drugą osobę.",
link=_deadline_link(matter.id),
dedupe_key=f"deadline:{deadline.id}:unconfirmed",
):
sent += 1
return sent
def _run_correspondence(db: DbSession, today: dt.date) -> int:
"""Undated authoritative post first — each of those is a clock that may already be running."""
sent = 0
recipients = notify.admins(db)
# The default page size for this list is a display limit. A background job that skipped the
# 51st undated item would skip exactly the pile nobody has looked at, so it scans far wider
# — and says so when it hits the cap rather than truncating in silence.
undated = corr_svc.undated(db, limit=SCAN_LIMIT)
if len(undated) == SCAN_LIMIT:
log.warning("Reminder scan hit the %d-item cap for undated correspondence; "
"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():
if notify.push(
db, user.id, kind=NotificationKind.service_date_missing,
title=f"Brak daty doręczenia: {item.subject}",
body=f"{item.channel.value} — bez daty doręczenia nie ma od czego liczyć terminu.",
link="#/inbox",
dedupe_key=f"corr:{item.id}:undated",
):
sent += 1
stale_before = dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=INBOX_STALE_DAYS)
stale = db.scalars(
select(Correspondence).where(
Correspondence.status == CorrespondenceStatus.unassigned,
Correspondence.created_at <= stale_before,
).limit(SCAN_LIMIT)
).all()
for item in stale:
for user in recipients:
if notify.push(
db, user.id, kind=NotificationKind.correspondence_unassigned,
title=f"Nieprzypisana korespondencja: {item.subject}",
body=f"Czeka w skrzynce od {item.created_at.date().isoformat()}.",
link="#/inbox",
dedupe_key=f"corr:{item.id}:unassigned",
):
sent += 1
return sent
def _run_conflicts(db: DbSession, today: dt.date) -> int:
"""A pending check blocks a matter from being opened, so it is worth chasing quickly."""
sent = 0
stale_before = dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=CONFLICT_STALE_DAYS)
checks = db.scalars(
select(ConflictCheck).where(
ConflictCheck.outcome == ConflictOutcome.pending,
ConflictCheck.created_at <= stale_before,
).limit(SCAN_LIMIT)
).all()
recipients = notify.admins(db)
for check in checks:
extra = [db.get(AppUser, check.run_by)] if check.run_by else []
for user in {u.id: u for u in recipients + [u for u in extra if u]}.values():
if notify.push(
db, user.id, kind=NotificationKind.conflict_pending,
title=f"Konflikt interesów bez rozstrzygnięcia: {check.subject}",
body=f"{check.hit_count} trafień — dopóki nie ma decyzji, sprawy nie da się "
"otworzyć.",
link="#/intake",
dedupe_key=f"conflict:{check.id}:pending",
):
sent += 1
return sent
def run(db: DbSession, today: dt.date | None = None) -> dict:
"""One pass. Safe to call as often as you like — see the module docstring."""
today = today or dt.date.today()
counts = {
"deadlines": _run_deadlines(db, today),
"correspondence": _run_correspondence(db, today),
"conflicts": _run_conflicts(db, today),
}
db.commit()
counts["total"] = sum(counts.values())
log.info("Reminder run for %s: %s", today.isoformat(), counts)
return counts
async def scheduler_loop() -> None:
"""Run `run()` on an interval, as an asyncio task in the app lifespan.
Same shape as Galena's backup scheduler, and the same caveat: it is an in-process task, so
in a multi-instance deployment it must run on ONE instance only. That is survivable here in
a way it would not be for most schedulers — every reminder is deduplicated by a database
constraint, so a second instance racing the first produces duplicate work, not duplicate
notifications.
A failure is logged and the loop continues: a reminder engine that dies silently on one bad
row is worse than one that skips a cycle.
"""
import asyncio
from ..config import get_settings
from ..db import SessionLocal
settings = get_settings()
if not settings.reminders_enabled:
log.info("Reminder scheduler disabled (REMINDERS_ENABLED=false).")
return
interval = max(1, settings.reminder_interval_hours) * 3600
# A short delay so startup — migrations, the first requests — is not competing with a scan.
await asyncio.sleep(15)
while True:
try:
db = SessionLocal()
try:
await asyncio.to_thread(run, db)
finally:
db.close()
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001 — never let one bad cycle kill the loop
log.exception("Reminder run failed; continuing.")
await asyncio.sleep(interval)
+342
View File
@@ -0,0 +1,342 @@
"""The numbers partners actually ask for.
Read-only, and every one of them filtered to the matters the reader may see — a management
report that quietly includes a matter someone is walled off from is a leak wearing a spreadsheet.
Definitions, because these words mean subtly different things at different firms and a report
whose basis is unstated is worse than no report:
- **Standard value** — recorded billable time at its snapshot rate, *before* write-offs. What
the work would have been worth if nobody had discounted it.
- **Write-off** — standard value minus what was actually put on the clock after reductions.
- **Billed** — time that reached an *issued* invoice. Time sitting on a draft is not billed;
time on a cancelled invoice was released back to unbilled and is not billed either.
- **Billing realisation** — billed ÷ standard. How much of the work's nominal value survived to
an invoice.
- **Collection realisation** — collected ÷ invoiced, net of VAT. VAT is not revenue.
- **Utilisation** — billable minutes ÷ target minutes, where target is Polish working days in
the period × `target_hours_per_day`. Public holidays are excluded properly; counting Christmas
as available flatters everyone by a few per cent.
- **Lock-up** — WIP days + debtor days: roughly how long a złoty of work waits to become cash.
- **Profitability** — billed minus cost of time minus unrecharged disbursements. Cost of time
needs `lawyer_profile.cost_rate_minor`; a matter with any uncosted time is reported as
**incomplete** rather than given a flattering number computed from zeroes.
These iterate in Python over a permission-filtered set rather than aggregating in SQL. At a
firm's data volume that is not the bottleneck, and it keeps one definition of how time becomes
money (`TimeEntry.amount_minor`) instead of a second one written in SQL that can drift from it.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import InvoiceStatus
from ..models import AppUser, Expense, Invoice, LawyerProfile, Matter, Node, TimeEntry
from . import authz, billing, settings as settings_svc, workdays
# Invoice statuses that count as "the client has been asked to pay".
ISSUED = (InvoiceStatus.issued, InvoiceStatus.paid)
AGE_BUCKETS = (
("current", 0), # not yet due
("d1_30", 30),
("d31_60", 60),
("d61_90", 90),
("d90_plus", None), # older than 90 days
)
def default_period() -> tuple[dt.date, dt.date]:
"""Year to date — the window a partner means when they don't say."""
today = dt.date.today()
return dt.date(today.year, 1, 1), today
def visible_matters(db: DbSession, user: AppUser) -> list[Matter]:
matters = list(db.scalars(select(Matter)).all())
if not matters:
return []
nodes = list(
db.scalars(select(Node).where(Node.id.in_({m.node_id for m in matters}))).all()
)
readable = authz.readable_node_ids(db, user, nodes)
return [m for m in matters if m.node_id in readable]
def _standard_minor(entry: TimeEntry) -> int:
"""Value before any write-off, at the entry's snapshot rate."""
if not entry.billable or not entry.rate_minor:
return 0
return (entry.minutes * entry.rate_minor) // 60
def _issued_invoice_ids(db: DbSession, matter_ids: set[uuid.UUID]) -> set[uuid.UUID]:
if not matter_ids:
return set()
return set(
db.scalars(
select(Invoice.id).where(
Invoice.matter_id.in_(matter_ids), Invoice.status.in_(ISSUED)
)
).all()
)
# ── realisation ───────────────────────────────────────────────────────────────
def realisation(db: DbSession, user: AppUser, date_from: dt.date, date_to: dt.date) -> dict:
"""What happened to the value of the work done in this period."""
matters = visible_matters(db, user)
matter_ids = {m.id for m in matters}
if not matter_ids:
return {"standard_minor": 0, "written_off_minor": 0, "billable_minor": 0,
"billed_minor": 0, "unbilled_minor": 0,
"write_off_rate": None, "billing_realisation": None,
"invoiced_net_minor": 0, "collected_net_minor": 0,
"collection_realisation": None}
entries = list(
db.scalars(
select(TimeEntry).where(
TimeEntry.matter_id.in_(matter_ids),
TimeEntry.work_date >= date_from,
TimeEntry.work_date <= date_to,
)
).all()
)
issued_ids = _issued_invoice_ids(db, matter_ids)
standard = sum(_standard_minor(e) for e in entries)
billable = sum(e.amount_minor for e in entries)
billed = sum(e.amount_minor for e in entries if e.invoice_id in issued_ids)
unbilled = sum(e.amount_minor for e in entries if e.invoice_id is None)
# Collection is an invoice-level question, over invoices ISSUED in the period.
invoices = [
i for i in db.scalars(
select(Invoice).where(
Invoice.matter_id.in_(matter_ids), Invoice.status.in_(ISSUED)
)
).all()
if i.issued_on and date_from <= i.issued_on <= date_to
]
invoiced_net = sum(i.net_minor for i in invoices)
# Payments arrive gross; only the net share is revenue.
collected_net = sum(
(i.paid_minor * i.net_minor) // i.gross_minor if i.gross_minor else 0
for i in invoices
)
def ratio(part: int, whole: int) -> float | None:
return round(part / whole, 4) if whole else None
return {
"standard_minor": standard,
"written_off_minor": standard - billable,
"billable_minor": billable,
"billed_minor": billed,
"unbilled_minor": unbilled,
"write_off_rate": ratio(standard - billable, standard),
"billing_realisation": ratio(billed, standard),
"invoiced_net_minor": invoiced_net,
"collected_net_minor": collected_net,
"collection_realisation": ratio(collected_net, invoiced_net),
}
# ── utilisation ───────────────────────────────────────────────────────────────
def utilisation(db: DbSession, user: AppUser, date_from: dt.date, date_to: dt.date) -> dict:
"""Billable time per person against the working days actually available."""
matters = visible_matters(db, user)
matter_ids = {m.id for m in matters}
target_hours = float(settings_svc.get(db, "target_hours_per_day") or 6)
days = workdays.working_days(date_from, date_to)
target_minutes = int(days * target_hours * 60)
rows: dict[uuid.UUID, dict] = {}
if matter_ids:
for entry in db.scalars(
select(TimeEntry).where(
TimeEntry.matter_id.in_(matter_ids),
TimeEntry.work_date >= date_from,
TimeEntry.work_date <= date_to,
)
).all():
row = rows.setdefault(entry.user_id, {"recorded": 0, "billable": 0})
row["recorded"] += entry.minutes
row["billable"] += entry.billable_minutes
people = list(
db.scalars(select(AppUser).where(AppUser.is_active.is_(True))
.order_by(AppUser.full_name)).all()
)
out = []
for person in people:
row = rows.get(person.id, {"recorded": 0, "billable": 0})
out.append({
"user_id": str(person.id), "name": person.full_name,
"recorded_minutes": row["recorded"],
"billable_minutes": row["billable"],
"target_minutes": target_minutes,
"utilisation": round(row["billable"] / target_minutes, 4)
if target_minutes else None,
})
return {
"working_days": days,
"target_hours_per_day": target_hours,
"target_minutes": target_minutes,
"people": out,
}
# ── profitability ─────────────────────────────────────────────────────────────
def profitability(db: DbSession, user: AppUser, date_from: dt.date,
date_to: dt.date, limit: int = 100) -> list[dict]:
"""Billed minus the cost of the time and the disbursements nobody recharged."""
matters = visible_matters(db, user)
if not matters:
return []
matter_ids = {m.id for m in matters}
issued_ids = _issued_invoice_ids(db, matter_ids)
costs = {
p.user_id: p.cost_rate_minor
for p in db.scalars(select(LawyerProfile)).all()
}
entries: dict[uuid.UUID, list[TimeEntry]] = {}
for entry in db.scalars(
select(TimeEntry).where(
TimeEntry.matter_id.in_(matter_ids),
TimeEntry.work_date >= date_from,
TimeEntry.work_date <= date_to,
)
).all():
entries.setdefault(entry.matter_id, []).append(entry)
expenses: dict[uuid.UUID, list[Expense]] = {}
for cost in db.scalars(select(Expense).where(Expense.matter_id.in_(matter_ids))).all():
expenses.setdefault(cost.matter_id, []).append(cost)
out = []
for matter in matters:
mine = entries.get(matter.id, [])
if not mine:
continue
billed = sum(e.amount_minor for e in mine if e.invoice_id in issued_ids)
cost_of_time = 0
incomplete = False
for entry in mine:
rate = costs.get(entry.user_id)
if rate is None:
incomplete = True
continue
cost_of_time += (entry.minutes * rate) // 60
# A disbursement the firm swallowed is a cost; one recharged to the client is not.
unrecharged = sum(c.amount_minor for c in expenses.get(matter.id, [])
if not c.billable)
out.append({
"matter_id": str(matter.id), "reference": matter.reference, "name": matter.name,
"billed_minor": billed,
"cost_of_time_minor": cost_of_time,
"unrecharged_expenses_minor": unrecharged,
"margin_minor": billed - cost_of_time - unrecharged,
"margin_rate": round((billed - cost_of_time - unrecharged) / billed, 4)
if billed else None,
# True when somebody on this matter has no cost rate, so the margin flatters.
"incomplete": incomplete,
})
out.sort(key=lambda r: r["margin_minor"])
return out[:limit]
# ── lock-up and debt ──────────────────────────────────────────────────────────
def lock_up(db: DbSession, user: AppUser, date_from: dt.date, date_to: dt.date) -> dict:
"""How long a złoty of work waits to become cash."""
matters = visible_matters(db, user)
matter_ids = {m.id for m in matters}
wip = outstanding = 0
for matter in matters:
figures = billing.matter_financials(db, matter)
wip += figures["wip_minor"] + figures["unbilled_expenses_minor"]
outstanding += figures["outstanding_minor"]
invoices = [
i for i in (
db.scalars(
select(Invoice).where(
Invoice.matter_id.in_(matter_ids), Invoice.status.in_(ISSUED)
)
).all() if matter_ids else []
)
if i.issued_on and date_from <= i.issued_on <= date_to
]
billed_net = sum(i.net_minor for i in invoices)
days = max((date_to - date_from).days + 1, 1)
per_day = billed_net / days
def as_days(value: int) -> float | None:
return round(value / per_day, 1) if per_day else None
return {
"wip_minor": wip,
"outstanding_minor": outstanding,
"billed_net_minor": billed_net,
"period_days": days,
"wip_days": as_days(wip),
"debtor_days": as_days(outstanding),
"lock_up_days": round((as_days(wip) or 0) + (as_days(outstanding) or 0), 1)
if per_day else None,
}
def aged_debt(db: DbSession, user: AppUser, today: dt.date | None = None) -> dict:
"""Unpaid issued invoices bucketed by how far past due they are."""
today = today or dt.date.today()
matters = {m.id: m for m in visible_matters(db, user)}
if not matters:
return {"buckets": {k: 0 for k, _ in AGE_BUCKETS}, "total_minor": 0, "invoices": []}
buckets = {key: 0 for key, _ in AGE_BUCKETS}
rows = []
for invoice in db.scalars(
select(Invoice).where(
Invoice.matter_id.in_(set(matters)), Invoice.status == InvoiceStatus.issued
)
).all():
outstanding = invoice.gross_minor - invoice.paid_minor
if outstanding <= 0:
continue
overdue = (today - invoice.due_on).days if invoice.due_on else 0
key = "current"
if overdue > 0:
for name, upper in AGE_BUCKETS[1:]:
if upper is None or overdue <= upper:
key = name
break
buckets[key] += outstanding
matter = matters[invoice.matter_id]
rows.append({
"invoice_id": str(invoice.id), "number": invoice.number,
"matter_reference": matter.reference, "matter_name": matter.name,
"due_on": invoice.due_on.isoformat() if invoice.due_on else None,
"days_overdue": max(overdue, 0),
"outstanding_minor": outstanding, "bucket": key,
})
rows.sort(key=lambda r: -r["days_overdue"])
return {"buckets": buckets, "total_minor": sum(buckets.values()), "invoices": rows[:100]}
def overview(db: DbSession, user: AppUser, date_from: dt.date, date_to: dt.date) -> dict:
"""Everything the reports screen shows, in one call."""
return {
"date_from": date_from.isoformat(),
"date_to": date_to.isoformat(),
"realisation": realisation(db, user, date_from, date_to),
"utilisation": utilisation(db, user, date_from, date_to),
"lock_up": lock_up(db, user, date_from, date_to),
"aged_debt": aged_debt(db, user),
"profitability": profitability(db, user, date_from, date_to, limit=20),
}
+58
View File
@@ -0,0 +1,58 @@
"""Instance settings as auditable key/value rows. Copied from Galena's pattern — see SHARED.md.
Secrets are NEVER stored here; they come from the environment only."""
from __future__ import annotations
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..models import AppSetting
DEFAULTS = {
"firm_name": "Kancelaria",
# `law_firm` (default) or `in_house`. An in-house legal department runs the same matters,
# deadlines and conflicts, but bills nobody: it issues no invoices, has no court-appointed
# work, and its "client" is an internal business unit. One setting rather than a separate
# product — the differences are a handful of fields, not a different domain.
"practice_mode": "law_firm",
# Default hourly rate in grosze — 450,00 PLN.
"default_rate_minor": "45000",
"currency": "PLN",
# How far ahead the dashboard looks for deadlines.
"deadline_horizon_days": "14",
# Billable hours expected of a full-time fee earner per working day. Drives utilisation;
# the denominator is Polish working days, public holidays excluded.
"target_hours_per_day": "6",
}
def get(db: DbSession, key: str, default: str | None = None) -> str | None:
row = db.get(AppSetting, key)
if row is not None:
return row.value
return DEFAULTS.get(key, default)
def get_int(db: DbSession, key: str, default: int = 0) -> int:
raw = get(db, key)
try:
return int(raw) if raw is not None else default
except (TypeError, ValueError):
return default
def all_settings(db: DbSession) -> dict:
stored = {r.key: r.value for r in db.scalars(select(AppSetting)).all()}
return {**DEFAULTS, **stored}
def put(db: DbSession, key: str, value: str, actor_id=None) -> AppSetting:
row = db.get(AppSetting, key)
if row is None:
row = AppSetting(key=key, value=value, updated_by=actor_id)
db.add(row)
else:
row.value = value
row.updated_by = actor_id
db.flush()
return row
+109
View File
@@ -0,0 +1,109 @@
"""Dashboard figures. Read-only, permission-filtered, and deliberately few.
The pulpit answers four questions a lawyer actually has at 9am: what is due, what still needs a
second pair of eyes, what have I recorded this week, and what is waiting at intake.
"""
from __future__ import annotations
import datetime as dt
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import ConflictOutcome, MatterStatus
from ..models import AppUser, ConflictCheck, Lead, Matter, Node
from . import (
authz,
correspondence,
deadlines as deadlines_svc,
settings as settings_svc,
timelog,
)
def dashboard(db: DbSession, user: AppUser) -> dict:
today = dt.date.today()
week_start = today - dt.timedelta(days=today.weekday())
horizon = settings_svc.get_int(db, "deadline_horizon_days", 14)
upcoming = deadlines_svc.upcoming(db, user, days=horizon)
overdue = [(d, m) for d, m in upcoming if d.due_date < today]
unconfirmed = deadlines_svc.unconfirmed(db, user)
open_matters = list(
db.scalars(select(Matter).where(Matter.status == MatterStatus.open)).all()
)
node_ids = {m.node_id for m in open_matters}
found = (
list(db.scalars(select(Node).where(Node.id.in_(node_ids))).all()) if node_ids else []
)
readable = authz.readable_node_ids(db, user, found)
visible_matters = [m for m in open_matters if m.node_id in readable]
minutes_week = timelog.user_minutes_between(db, user.id, week_start, today)
pending_conflicts = len(
db.scalars(
select(ConflictCheck.id).where(ConflictCheck.outcome == ConflictOutcome.pending)
).all()
)
open_leads = len(
db.scalars(select(Lead.id).where(Lead.matter_id.is_(None))).all()
)
# 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)
return {
"cards": {
"deadlines_due": len(upcoming),
"deadlines_overdue": len(overdue),
"deadlines_unconfirmed": len(unconfirmed),
"open_matters": len(visible_matters),
"my_matters": len([m for m in visible_matters
if m.responsible_lawyer_id == user.id]),
"minutes_this_week": minutes_week,
"pending_conflicts": pending_conflicts,
"open_leads": open_leads,
"inbox": inbox_count,
# Incoming post from an authoritative channel with no service date yet. Each one is
# a clock that may already be running while nobody is watching it, so it gets its
# own number rather than hiding inside the inbox count.
"undated_service": undated_count,
"horizon_days": horizon,
},
"deadlines": [
{
"id": str(d.id),
"title": d.title,
"due_date": d.due_date.isoformat(),
"kind": d.kind.value,
"source": d.source.value,
"overdue": d.due_date < today,
"days_left": (d.due_date - today).days,
"confirmed": d.confirmed_at is not None,
"matter_id": str(m.id),
"matter_reference": m.reference,
"matter_name": m.name,
}
for d, m in upcoming[:25]
],
# Same shape as `deadlines` above — the console renders both through one table, so a
# missing field here shows up as "undefined" rather than as an error.
"unconfirmed": [
{
"id": str(d.id),
"title": d.title,
"due_date": d.due_date.isoformat(),
"kind": d.kind.value,
"source": d.source.value,
"overdue": d.due_date < today,
"days_left": (d.due_date - today).days,
"confirmed": False,
"matter_id": str(m.id),
"matter_reference": m.reference,
"matter_name": m.name,
}
for d, m in unconfirmed[:10]
],
}
+205
View File
@@ -0,0 +1,205 @@
"""Time entries (karta czasu pracy).
Time is the product, so the rules are strict: integer minutes, an explicit narrative the client
will read, and a rate snapshot taken at entry so a later rate-card change never rewrites
history. An entry that has reached an invoice is frozen — Phase 3 adds the invoice table, and
`invoice_id` already guards against editing billed time.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import func, select
from sqlalchemy.orm import Session as DbSession
from ..enums import NodeRole
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, Matter, TimeEntry
from . import rates
# 0.1 h. The UI works in these units and so does every Polish law firm's billing guideline.
INCREMENT_MINUTES = 6
MAX_MINUTES_PER_ENTRY = 24 * 60
def round_to_increment(minutes: int) -> int:
"""Round up to the next 6-minute unit. Up, not nearest: a started unit is a billed unit,
which is the convention every client's billing guidelines already assume."""
if minutes <= 0:
return 0
return -(-minutes // INCREMENT_MINUTES) * INCREMENT_MINUTES
def parse_duration(value: str | int | float) -> int:
"""Accept what people actually type: 90, '90m', '1.5', '1,5', '1:30', '1h30'."""
if isinstance(value, (int, float)):
return int(round(float(value) * 60)) if float(value) < 12 else int(value)
raw = str(value).strip().lower().replace(",", ".")
if not raw:
raise ValidationError("Podaj czas pracy.")
if ":" in raw:
hours, _, mins = raw.partition(":")
try:
return int(hours or 0) * 60 + int(mins or 0)
except ValueError:
raise ValidationError("Nie rozumiem tego czasu. Spróbuj np. 1:30.") from None
if raw.endswith("m"):
try:
return int(float(raw[:-1]))
except ValueError:
raise ValidationError("Nie rozumiem tego czasu. Spróbuj np. 90m.") from None
if "h" in raw:
hours, _, mins = raw.partition("h")
try:
return int(float(hours or 0) * 60) + int(float(mins or 0))
except ValueError:
raise ValidationError("Nie rozumiem tego czasu. Spróbuj np. 1h30.") from None
try:
number = float(raw)
except ValueError:
raise ValidationError("Nie rozumiem tego czasu. Spróbuj np. 1.5 albo 90m.") from None
# A bare number under 12 reads as hours ("1.5"), above that as minutes ("90").
return int(round(number * 60)) if number < 12 else int(number)
def get_entry(db: DbSession, entry_id: uuid.UUID) -> TimeEntry:
row = db.get(TimeEntry, entry_id)
if row is None:
raise NotFoundError("Nie znaleziono wpisu czasu.")
return row
def create(
db: DbSession,
user: AppUser,
matter: Matter,
*,
minutes: int,
narrative: str,
work_date: dt.date | None = None,
billable: bool = True,
activity_code: str | None = None,
rate_minor: int | None = None,
for_user_id: uuid.UUID | None = None,
) -> TimeEntry:
narrative = (narrative or "").strip()
if not narrative:
raise ValidationError("Opis czynności jest wymagany — zobaczy go klient.")
minutes = round_to_increment(int(minutes))
if minutes <= 0:
raise ValidationError("Czas pracy musi być większy od zera.")
if minutes > MAX_MINUTES_PER_ENTRY:
raise ValidationError("Jeden wpis nie może przekraczać 24 godzin.")
author_id = for_user_id or user.id
on_date = work_date or dt.date.today()
if rate_minor is None:
# Resolved from the rate-card hierarchy for the date of the WORK, not today: recording
# last month's time next Tuesday must price it at last month's rate. The result is
# snapshotted onto the row, so a card edited tomorrow cannot re-price it.
rate_minor = rates.resolve(db, matter, author_id, on_date).rate_minor
row = TimeEntry(
matter_id=matter.id,
user_id=author_id,
work_date=on_date,
minutes=minutes,
narrative=narrative,
billable=billable,
activity_code=activity_code,
rate_minor=rate_minor,
)
db.add(row)
db.flush()
return row
def assert_can_edit(entry: TimeEntry, user: AppUser, role: NodeRole) -> None:
"""Own entries are editable by their author; anyone else needs approver. Billed time is
frozen for everyone — correcting it is a credit note, not an edit."""
if entry.invoice_id is not None:
raise ConflictError("Ten wpis trafił już na fakturę i nie można go zmienić.")
if entry.user_id != user.id and NodeRole.rank(role) < NodeRole.rank(NodeRole.approver):
raise ConflictError("Cudze wpisy czasu może zmieniać osoba zatwierdzająca.")
def update(db: DbSession, entry: TimeEntry, **fields) -> TimeEntry:
if "minutes" in fields and fields["minutes"] is not None:
fields["minutes"] = round_to_increment(int(fields["minutes"]))
if fields["minutes"] <= 0:
raise ValidationError("Czas pracy musi być większy od zera.")
if "narrative" in fields and fields["narrative"] is not None:
if not str(fields["narrative"]).strip():
raise ValidationError("Opis czynności jest wymagany.")
for key, value in fields.items():
if value is not None and hasattr(entry, key):
setattr(entry, key, value)
if entry.write_off_minutes > entry.minutes:
entry.write_off_minutes = entry.minutes
db.flush()
return entry
def delete(db: DbSession, entry: TimeEntry) -> None:
if entry.invoice_id is not None:
raise ConflictError("Ten wpis trafił już na fakturę i nie można go usunąć.")
db.delete(entry)
def for_matter(db: DbSession, matter: Matter, limit: int = 500) -> list[tuple[TimeEntry, AppUser]]:
return list(
db.execute(
select(TimeEntry, AppUser)
.join(AppUser, AppUser.id == TimeEntry.user_id)
.where(TimeEntry.matter_id == matter.id)
.order_by(TimeEntry.work_date.desc(), TimeEntry.created_at.desc())
.limit(limit)
).all()
)
def for_user(
db: DbSession, user_id: uuid.UUID, *, date_from: dt.date, date_to: dt.date
) -> list[tuple[TimeEntry, Matter]]:
return list(
db.execute(
select(TimeEntry, Matter)
.join(Matter, Matter.id == TimeEntry.matter_id)
.where(
TimeEntry.user_id == user_id,
TimeEntry.work_date >= date_from,
TimeEntry.work_date <= date_to,
)
.order_by(TimeEntry.work_date.desc())
).all()
)
def matter_totals(db: DbSession, matter: Matter) -> dict:
"""Recorded / billable minutes and unbilled value for one matter.
Computed in Python over one query rather than as SQL aggregates: the amount depends on
`TimeEntry.amount_minor`, and having exactly one definition of how time becomes money is
worth more than saving a pass over a few hundred rows."""
entries = list(
db.scalars(select(TimeEntry).where(TimeEntry.matter_id == matter.id)).all()
)
return {
"total_minutes": sum(e.minutes for e in entries),
"billable_minutes": sum(e.billable_minutes for e in entries),
"unbilled_minor": sum(e.amount_minor for e in entries if e.invoice_id is None),
}
def user_minutes_between(
db: DbSession, user_id: uuid.UUID, date_from: dt.date, date_to: dt.date
) -> int:
return int(
db.scalar(
select(func.coalesce(func.sum(TimeEntry.minutes), 0)).where(
TimeEntry.user_id == user_id,
TimeEntry.work_date >= date_from,
TimeEntry.work_date <= date_to,
)
)
or 0
)
+99
View File
@@ -0,0 +1,99 @@
"""Polish working days and public holidays. Pure — no database, no I/O.
Utilisation is billable hours over *available* hours, and available hours that count Christmas
Day flatter everyone by a few per cent. So the holidays are computed properly rather than
approximated by "weekdays".
Written here rather than inside `reports.py` because Phase 2 needs the same calendar: a KPC
deadline that falls on a Saturday, Sunday or public holiday moves to the next working day
(art. 115 k.c.), and `deadlines.derive` will call `next_working_day` when there is a real
service date to count from.
The movable feasts hang off Easter, computed with the anonymous Gregorian algorithm.
"""
from __future__ import annotations
import datetime as dt
import functools
# Fixed-date public holidays (month, day).
FIXED_HOLIDAYS = (
(1, 1), # Nowy Rok
(1, 6), # Trzech Króli
(5, 1), # Święto Pracy
(5, 3), # Święto Konstytucji 3 Maja
(8, 15), # Wniebowzięcie NMP
(11, 1), # Wszystkich Świętych
(11, 11), # Narodowe Święto Niepodległości
(12, 25), # Boże Narodzenie
(12, 26), # drugi dzień Bożego Narodzenia
)
# Days after Easter Sunday that are also public holidays.
EASTER_OFFSETS = (
1, # Poniedziałek Wielkanocny
49, # Zielone Świątki (Pentecost)
60, # Boże Ciało (Corpus Christi)
)
def easter(year: int) -> dt.date:
"""Easter Sunday, anonymous Gregorian algorithm."""
a = year % 19
b, c = divmod(year, 100)
d, e = divmod(b, 4)
f = (b + 8) // 25
g = (b - f + 1) // 3
h = (19 * a + b - d - g + 15) % 30
i, k = divmod(c, 4)
lam = (32 + 2 * e + 2 * i - h - k) % 7
m = (a + 11 * h + 22 * lam) // 451
month, day = divmod(h + lam - 7 * m + 114, 31)
return dt.date(year, month, day + 1)
@functools.lru_cache(maxsize=64)
def holidays(year: int) -> frozenset[dt.date]:
"""Every Polish public holiday in `year`.
Easter Sunday itself is included: it is a public holiday, and although it is always a Sunday
the set is used for "is this a non-working day" checks where being complete matters more
than being minimal."""
days = {dt.date(year, month, day) for month, day in FIXED_HOLIDAYS}
sunday = easter(year)
days.add(sunday)
days.update(sunday + dt.timedelta(days=offset) for offset in EASTER_OFFSETS)
return frozenset(days)
def is_holiday(day: dt.date) -> bool:
return day in holidays(day.year)
def is_working_day(day: dt.date) -> bool:
"""Monday–Friday and not a public holiday."""
return day.weekday() < 5 and not is_holiday(day)
def working_days(start: dt.date, end: dt.date) -> int:
"""Working days in the inclusive range. Zero if the range is inverted."""
if end < start:
return 0
count = 0
day = start
while day <= end:
if is_working_day(day):
count += 1
day += dt.timedelta(days=1)
return count
def next_working_day(day: dt.date) -> dt.date:
"""The first working day on or after `day`.
art. 115 k.c. — a deadline falling on a Saturday, Sunday or public holiday runs to the next
working day. Not yet wired into `deadlines.derive`; that lands with the e-Doręczenia work,
when a real service date makes the arithmetic worth trusting."""
while not is_working_day(day):
day += dt.timedelta(days=1)
return day
+15
View File
@@ -0,0 +1,15 @@
[project]
name = "sygna-backend"
version = "0.1.0"
description = "Sygna — practice management for Polish law firms (FastAPI backend)."
requires-python = ">=3.12"
license = { text = "Apache-2.0" }
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q"
pythonpath = ["."] # put backend/ (rootdir) on sys.path so `import app` works from `cd backend && pytest`
[tool.ruff]
line-length = 100
target-version = "py312"
+4
View File
@@ -0,0 +1,4 @@
-r requirements.txt
pytest==8.3.4
pytest-cov==6.0.0
pip-licenses==5.0.0 # CI license gate
+35
View File
@@ -0,0 +1,35 @@
# Versions pinned to Galena's, so a future merge has no dependency reconciliation.
# Every entry is permissive — the CI license gate (scripts/license_gate.py) denies GPL/AGPL/SSPL.
# Web framework
fastapi==0.115.6
uvicorn[standard]==0.34.0
python-multipart==0.0.20 # multipart/form-data uploads (Apache-2.0)
# Validation / settings
pydantic==2.10.4
pydantic-settings==2.7.1
# email validation is done in-app via a regex validator (schemas.Email) — no email-validator dependency
# DB / ORM / migrations
SQLAlchemy==2.0.50
alembic==1.14.0
pg8000==1.31.2 # pure-Python PostgreSQL driver, BSD-3-Clause (no LGPL, no libpq)
# Auth
argon2-cffi==23.1.0 # Argon2id password hashing (MIT)
# Outbound HTTP — the ONE client, used only from app/integrations/ (invariant 8).
httpx==0.28.1 # BSD-3-Clause
# OpenTelemetry (OTLP → OTel Collector) — optional, import-guarded in observability.py
opentelemetry-sdk==1.42.1
opentelemetry-exporter-otlp-proto-grpc==1.42.1
opentelemetry-instrumentation-fastapi==0.63b1
opentelemetry-instrumentation-sqlalchemy==0.63b1
# Planned for later phases (NOT installed yet — added when the phase starts):
# cryptography — AES-256-GCM, if Sygna stores secrets at rest (Apache-2.0/BSD)
# python-docx — document generation from templates (MIT) [Phase 5]
# signxml — XAdES signing for KSeF (Apache-2.0) [Phase 2]
# pyHanko — PAdES signing for PDF pleadings (MIT) [Phase 5]
+39
View File
@@ -0,0 +1,39 @@
"""CI license gate: fail the build if any installed dependency is strong copyleft
(GPL / AGPL / SSPL). LGPL is allowed by policy; MPL/Apache/MIT/BSD/HPND/PSF are fine."""
from __future__ import annotations
import json
import subprocess
import sys
DENY = ("AGPL", "SSPL") # always denied
DENY_GPL_EXCEPT_LGPL = "GPL" # deny GPL but allow LGPL
def main() -> int:
out = subprocess.run(
[sys.executable, "-m", "piplicenses", "--format=json"],
capture_output=True, text=True,
)
if out.returncode != 0 or not out.stdout.strip():
# fall back to the console script name (module form may be unavailable)
out = subprocess.run(["pip-licenses", "--format=json"], capture_output=True, text=True)
pkgs = json.loads(out.stdout or "[]")
violations = []
for p in pkgs:
lic = (p.get("License") or "").upper()
if any(tok in lic for tok in DENY):
violations.append((p["Name"], p["License"]))
elif DENY_GPL_EXCEPT_LGPL in lic and "LGPL" not in lic:
violations.append((p["Name"], p["License"]))
if violations:
print("License gate FAILED — disallowed (strong copyleft) dependencies:")
for name, lic in violations:
print(f" - {name}: {lic}")
return 1
print(f"License gate OK — {len(pkgs)} packages, no GPL/AGPL/SSPL.")
return 0
if __name__ == "__main__":
sys.exit(main())
+93
View File
@@ -0,0 +1,93 @@
"""Fail the build when a file shared with Galena has drifted.
SHARED.md is the contract: rows in its "Byte-identical" table whose Galena column is exactly
`same` must match Galena's copy byte for byte. Rows that say `same + something` are documented
additive divergences and are only reported, never failed.
This is the cheap half of Stage B. Extracting a real shared library is the expensive half, and
it is worth nothing if the two copies have already drifted — so the check comes first.
Galena is expected at ../Galena (override with GALENA_REPO). When it is absent — CI, a fresh
clone, anyone who only has this repository — the check SKIPS rather than fails: a contributor
who does not have both repositories checked out has not done anything wrong.
"""
from __future__ import annotations
import os
import pathlib
import re
import sys
HERE = pathlib.Path(__file__).resolve()
SYGNA = HERE.parents[2]
GALENA = pathlib.Path(os.environ.get("GALENA_REPO") or SYGNA.parent / "Galena")
SHARED_MD = SYGNA / "SHARED.md"
ROW = re.compile(r"^\|\s*`([^`]+)`\s*\|\s*([^|]+?)\s*\|")
def parse_shared() -> list[tuple[str, str]]:
"""(path, galena-column) rows from the Byte-identical table."""
text = SHARED_MD.read_text(encoding="utf-8")
start = text.index("## Byte-identical")
end = text.index("\n## ", start)
rows = []
for line in text[start:end].splitlines():
m = ROW.match(line)
if m and "/" in m.group(1):
rows.append((m.group(1), m.group(2)))
return rows
def main() -> int:
if not GALENA.exists():
print(f"Shared-file check SKIPPED — Galena not found at {GALENA}.")
print("Set GALENA_REPO to run it.")
return 0
if not SHARED_MD.exists():
print("SHARED.md is missing — it is the contract; nothing to check against.")
return 1
rows = parse_shared()
if not rows:
print("No byte-identical rows parsed from SHARED.md — has the table format changed?")
return 1
drifted, missing, additive, clean = [], [], [], 0
for rel, galena_col in rows:
ours, theirs = SYGNA / rel, GALENA / rel
if not ours.exists() or not theirs.exists():
missing.append((rel, "sygna" if not ours.exists() else "galena"))
continue
same = ours.read_bytes() == theirs.read_bytes()
if galena_col.strip() != "same":
additive.append((rel, galena_col.strip(), same))
continue
if same:
clean += 1
else:
drifted.append(rel)
print(f"Shared-file check against {GALENA}")
print(f" {clean} byte-identical, {len(additive)} documented-additive, "
f"{len(drifted)} drifted, {len(missing)} missing")
for rel, note, same in additive:
print(f" ~ {rel}: documented divergence ({note})"
+ ("" if not same else " — now identical, consider tightening SHARED.md"))
for rel, where in missing:
print(f" ? {rel}: not present in {where}")
if drifted:
print("\nDrifted — these are declared byte-identical in SHARED.md but are not:")
for rel in drifted:
print(f" - {rel}")
print("\nChange shared files in BOTH repositories in the same commit, or move the row "
"to 'Same shape, intentionally adapted' and say why.")
return 1
if missing:
return 1
print("OK — every file declared byte-identical still is.")
return 0
if __name__ == "__main__":
sys.exit(main())
+8
View File
@@ -0,0 +1,8 @@
"""Point DATA_DIR at a throwaway temp dir before any app import."""
from __future__ import annotations
import os
import tempfile
os.environ.setdefault("DATA_DIR", tempfile.mkdtemp(prefix="sygna-test-"))
os.environ.setdefault("APP_ENV", "development")
+139
View File
@@ -0,0 +1,139 @@
{
"odpis": {
"rodzaj": "Aktualny",
"naglowekA": {
"rejestr": "RejP",
"numerKRS": "0000006865",
"stanZDnia": "10.08.2026",
"dataRejestracjiWKRS": "06.04.2001"
},
"dane": {
"dzial1": {
"danePodmiotu": {
"nazwa": "CD PROJEKT RED SPÓŁKA AKCYJNA",
"formaPrawna": "SPÓŁKA AKCYJNA",
"identyfikatory": {
"regon": "49270733300000",
"nip": "7342867148"
}
},
"siedzibaIAdres": {
"siedziba": {
"kraj": "POLSKA",
"wojewodztwo": "MAZOWIECKIE",
"powiat": "M.ST. WARSZAWA",
"gmina": "M.ST. WARSZAWA",
"miejscowosc": "WARSZAWA"
},
"adres": {
"ulica": "JAGIELLOŃSKA",
"nrDomu": "74",
"miejscowosc": "WARSZAWA",
"kodPocztowy": "03-301",
"poczta": "WARSZAWA",
"kraj": "POLSKA"
},
"adresPocztyElektronicznej": "GIELDA@CDPROJEKT.COM",
"adresStronyInternetowej": "WWW.CDPROJEKT.COM",
"adresDoDoreczenElektronicznychWpisanyDoBAE": "AE:PL-78699-92156-WWISD-24"
}
},
"dzial2": {
"reprezentacja": {
"nazwaOrganu": "ZARZĄD",
"sposobReprezentacji": "W PRZYPADKU ZARZĄDU JEDNOOSOBOWEGO DO REPREZENTOWANIA SPÓŁKI UPOWAŻNIONY JEST JEDNOOSOBOWO CZŁONEK ZARZĄDU.\nW PRZYPADKU POWOŁANIA ZARZĄDU WIELOOSOBOWEGO DO REPREZENTOWANIA SPÓŁKI UPOWAŻNIENI SĄ DWAJ CZŁONKOWIE ZARZĄDU DZIAŁAJĄCY ŁĄCZNIE ALBO JEDEN CZŁONEK ZARZĄDU DZIAŁAJĄCY ŁĄCZNIE Z PROKURENTEM.",
"sklad": [
{
"nazwisko": {
"nazwiskoICzlon": "N**********"
},
"imiona": {
"imie": "P****",
"imieDrugie": "M*****"
},
"identyfikator": {
"pesel": "7**********"
},
"funkcjaWOrganie": "CZŁONEK ZARZĄDU",
"czyZawieszona": false
},
{
"nazwisko": {
"nazwiskoICzlon": "B*******"
},
"imiona": {
"imie": "A***",
"imieDrugie": "K*****"
},
"identyfikator": {
"pesel": "7**********"
},
"funkcjaWOrganie": "CZŁONEK ZARZĄDU",
"czyZawieszona": false
},
{
"nazwisko": {
"nazwiskoICzlon": "N*********"
},
"imiona": {
"imie": "M*****",
"imieDrugie": "A******"
},
"identyfikator": {
"pesel": "7**********"
},
"funkcjaWOrganie": "CZŁONEK ZARZĄDU",
"czyZawieszona": false
}
]
},
"organNadzoru": [
{
"nazwa": "RADA NADZORCZA",
"sklad": [
{
"nazwisko": {
"nazwiskoICzlon": "I******"
},
"imiona": {
"imie": "M*****",
"imieDrugie": "P****"
},
"identyfikator": {
"pesel": "7**********"
}
},
{
"nazwisko": {
"nazwiskoICzlon": "K*******"
},
"imiona": {
"imie": "A***",
"imieDrugie": "M*****"
},
"identyfikator": {
"pesel": "6**********"
}
}
]
}
],
"prokurenci": [
{
"nazwisko": {
"nazwiskoICzlon": "T**********"
},
"imiona": {
"imie": "A********",
"imieDrugie": "M****"
},
"identyfikator": {
"pesel": "7**********"
},
"rodzajProkury": "ŁĄCZNA Z INNYM PROKURENTEM LUB CZŁONKIEM ZARZĄDU"
}
]
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
"""Role ranking and path inheritance. DB-free."""
from __future__ import annotations
from app.enums import NodeRole
from app.services.authz import ancestor_paths
def test_role_ordering():
assert NodeRole.rank(NodeRole.viewer) < NodeRole.rank(NodeRole.editor)
assert NodeRole.rank(NodeRole.editor) < NodeRole.rank(NodeRole.approver)
assert NodeRole.rank(NodeRole.approver) < NodeRole.rank(NodeRole.manager)
def test_no_role_ranks_below_every_role():
assert NodeRole.rank(None) == 0
assert NodeRole.rank(None) < NodeRole.rank(NodeRole.viewer)
def test_ancestor_paths_include_self():
assert ancestor_paths("/kancelaria/procesowy/kowalski") == [
"/kancelaria", "/kancelaria/procesowy", "/kancelaria/procesowy/kowalski",
]
def test_ancestor_paths_of_root():
assert ancestor_paths("/kancelaria") == ["/kancelaria"]
assert ancestor_paths("") == []
+338
View File
@@ -0,0 +1,338 @@
"""Money. Skipped unless SYGNA_RUN_INTEGRATION=1.
The rules worth failing a build over: an issued invoice cannot be edited, a number is only
handed out at issue, client money cannot go negative, and a credit note releases the work so it
can be re-billed rather than silently written off.
"""
from __future__ import annotations
import datetime as dt
import os
import uuid
import pytest
pytestmark = pytest.mark.skipif(
os.environ.get("SYGNA_RUN_INTEGRATION") != "1",
reason="needs a migrated + seeded Postgres; set SYGNA_RUN_INTEGRATION=1",
)
@pytest.fixture(scope="module")
def db():
from app.db import SessionLocal
session = SessionLocal()
try:
yield session
finally:
session.rollback()
session.close()
@pytest.fixture(scope="module")
def admin(db):
from app.services import auth as auth_svc
return auth_svc.find_user_by_email(
db, os.environ.get("BOOTSTRAP_ADMIN_EMAIL", "admin@example.com")
)
@pytest.fixture
def matter(db, admin):
from app.enums import NodeKind, PartyKind
from app.services import conflicts, matters as matters_svc, nodes as nodes_svc
from app.services import parties as parties_svc
tag = uuid.uuid4().hex[:8]
ws = nodes_svc.create_node(db, admin, parent=None, kind=NodeKind.workspace,
name=f"Rozliczenia {tag}")
client = parties_svc.create_party(db, admin, kind=PartyKind.organisation,
name=f"Klient {tag}")
check = conflicts.run(db, admin, subject=client.name)
m, _ = matters_svc.open_matter(
db, admin, name=f"Sprawa {tag}", client_party_id=client.id,
parent_node_id=ws.id, conflict_check_id=check.id, default_rate_minor=40000,
)
db.flush()
yield m
db.rollback()
def _time(db, admin, matter, minutes=60, narrative="Praca."):
from app.services import timelog
return timelog.create(db, admin, matter, minutes=minutes, narrative=narrative)
# ── expenses ─────────────────────────────────────────────────────────────────
def test_court_fees_default_to_passthrough(db, admin, matter):
"""A recharged court fee is not our supply, so no VAT of ours rides on it."""
from app.enums import ExpenseKind
from app.services import billing
fee = billing.add_expense(db, admin, matter, kind=ExpenseKind.court_fee,
description="Opłata od pozwu", amount_minor=925000)
travel = billing.add_expense(db, admin, matter, kind=ExpenseKind.travel,
description="Dojazd", amount_minor=20000)
assert fee.is_passthrough is True
assert travel.is_passthrough is False
def test_an_expense_paid_from_deposit_moves_the_ledger(db, admin, matter):
from app.enums import DepositMovementKind, ExpenseKind
from app.services import billing
billing.move_deposit(db, admin, matter, amount_minor=1_000_00,
kind=DepositMovementKind.deposit)
billing.add_expense(db, admin, matter, kind=ExpenseKind.court_fee,
description="Opłata", amount_minor=300_00, paid_from_deposit=True)
assert billing.deposit_for(db, matter).balance_minor == 700_00
def test_client_money_cannot_go_negative(db, admin, matter):
"""Not a convention — a CHECK constraint backs it, and the service refuses first."""
from app.enums import DepositMovementKind
from app.errors import ConflictError
from app.services import billing
billing.move_deposit(db, admin, matter, amount_minor=100_00,
kind=DepositMovementKind.deposit)
with pytest.raises(ConflictError):
billing.move_deposit(db, admin, matter, amount_minor=-100_01,
kind=DepositMovementKind.refund)
assert billing.deposit_for(db, matter).balance_minor == 100_00
# ── drafting ─────────────────────────────────────────────────────────────────
def test_a_draft_sweeps_up_unbilled_time_and_expenses(db, admin, matter):
from app.enums import ExpenseKind
from app.services import billing
_time(db, admin, matter, minutes=90) # 1.5 h @ 400,00 = 600,00
billing.add_expense(db, admin, matter, kind=ExpenseKind.court_fee,
description="Opłata od pozwu", amount_minor=100_00)
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter)
lines = billing.lines_of(db, invoice)
assert len(lines) == 2
# Time is standard-rated; the recharged court fee is not.
time_line = next(x for x in lines if not x.is_passthrough)
fee_line = next(x for x in lines if x.is_passthrough)
assert (time_line.net_minor, time_line.vat_rate) == (600_00, 23)
assert time_line.vat_minor == 138_00
assert (fee_line.net_minor, fee_line.vat_rate, fee_line.vat_minor) == (100_00, 0, 0)
assert invoice.net_minor == 700_00
assert invoice.vat_minor == 138_00
assert invoice.gross_minor == 838_00
def test_drafting_locks_the_work_and_deleting_releases_it(db, admin, matter):
from app.services import billing
entry = _time(db, admin, matter, minutes=60)
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter)
assert entry.invoice_id == invoice.id
assert billing.unbilled(db, matter) == ([], [])
billing.cancel_draft(db, invoice)
db.flush()
assert entry.invoice_id is None
assert len(billing.unbilled(db, matter)[0]) == 1
def test_nothing_to_bill_is_refused_rather_than_producing_an_empty_invoice(db, admin, matter):
from app.errors import ConflictError
from app.services import billing
with pytest.raises(ConflictError):
billing.draft_from_unbilled(db, admin, matter)
def test_vat_is_summed_per_line_not_taxed_on_the_total(db, admin, matter):
"""Three lines of 3,33 net: per-line VAT is 3×0,77 = 2,31, not 23% of 9,99 = 2,30."""
from app.services import billing
for _ in range(3):
_time(db, admin, matter, minutes=6) # 0.1 h @ 400,00 = 40,00
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter, group_time=False)
lines = billing.lines_of(db, invoice)
assert len(lines) == 3
assert invoice.vat_minor == sum(x.vat_minor for x in lines)
# ── the point of no return ───────────────────────────────────────────────────
def test_a_number_is_assigned_at_issue_not_at_draft(db, admin, matter):
"""A gap in an invoice sequence is a question from the tax office."""
from app.services import billing
_time(db, admin, matter)
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter)
assert invoice.number is None
billing.approve(db, invoice, admin)
billing.issue(db, invoice, admin)
assert invoice.number and invoice.number.startswith("FV ")
assert invoice.number.endswith(f"/{dt.date.today().year}")
assert invoice.due_on > invoice.issued_on
def test_issuing_requires_approval_first(db, admin, matter):
from app.errors import ConflictError
from app.services import billing
_time(db, admin, matter)
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter)
with pytest.raises(ConflictError):
billing.issue(db, invoice, admin)
def test_an_issued_invoice_cannot_be_edited_or_deleted(db, admin, matter):
from app.errors import ConflictError
from app.services import billing
_time(db, admin, matter)
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter)
billing.approve(db, invoice, admin)
billing.issue(db, invoice, admin)
with pytest.raises(ConflictError):
billing.assert_mutable(invoice)
with pytest.raises(ConflictError):
billing.cancel_draft(db, invoice)
def test_approval_records_who_read_the_narratives(db, admin, matter):
from app.services import billing
_time(db, admin, matter, narrative="Analiza akt i przygotowanie pisma.")
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter)
billing.approve(db, invoice, admin)
assert invoice.approved_by_id == admin.id
assert invoice.approved_at is not None
# ── payment and correction ───────────────────────────────────────────────────
def test_payment_closes_the_invoice_when_fully_settled(db, admin, matter):
from app.enums import InvoiceStatus
from app.services import billing
_time(db, admin, matter)
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter)
billing.approve(db, invoice, admin)
billing.issue(db, invoice, admin)
billing.register_payment(db, invoice, amount_minor=invoice.gross_minor - 100)
assert invoice.status == InvoiceStatus.issued
billing.register_payment(db, invoice, amount_minor=100)
assert invoice.status == InvoiceStatus.paid
assert invoice.paid_on is not None
def test_an_invoice_can_be_settled_from_client_money(db, admin, matter):
from app.enums import DepositMovementKind, InvoiceStatus
from app.services import billing
_time(db, admin, matter)
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter)
billing.approve(db, invoice, admin)
billing.issue(db, invoice, admin)
billing.move_deposit(db, admin, matter, amount_minor=invoice.gross_minor,
kind=DepositMovementKind.deposit)
billing.settle_from_deposit(db, invoice, admin, matter)
assert invoice.status == InvoiceStatus.paid
assert billing.deposit_for(db, matter).balance_minor == 0
def test_a_credit_note_mirrors_the_invoice_and_frees_the_work(db, admin, matter):
"""Correcting an issued invoice must not silently write the work off — it goes back to
unbilled so it can be re-billed properly."""
from app.enums import InvoiceKind, InvoiceStatus
from app.services import billing
entry = _time(db, admin, matter)
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter)
billing.approve(db, invoice, admin)
billing.issue(db, invoice, admin)
gross = invoice.gross_minor
note = billing.credit_note(db, invoice, admin, reason="Błędna stawka.")
assert note.kind == InvoiceKind.credit_note
assert note.corrects_invoice_id == invoice.id
assert note.gross_minor == -gross
assert invoice.status == InvoiceStatus.cancelled
db.flush()
assert entry.invoice_id is None
assert len(billing.unbilled(db, matter)[0]) == 1
def test_a_credit_note_needs_a_reason_and_only_one_per_invoice(db, admin, matter):
from app.errors import ConflictError, ValidationError
from app.services import billing
_time(db, admin, matter)
db.flush()
invoice = billing.draft_from_unbilled(db, admin, matter)
billing.approve(db, invoice, admin)
billing.issue(db, invoice, admin)
with pytest.raises(ValidationError):
billing.credit_note(db, invoice, admin, reason=" ")
billing.credit_note(db, invoice, admin, reason="Pomyłka.")
with pytest.raises(ConflictError):
billing.credit_note(db, invoice, admin, reason="Znowu.")
# ── the numbers partners ask for ─────────────────────────────────────────────
def test_matter_financials_separate_wip_from_billed_and_paid(db, admin, matter):
from app.services import billing
_time(db, admin, matter, minutes=60) # 400,00 WIP
db.flush()
figures = billing.matter_financials(db, matter)
assert figures["wip_minor"] == 400_00
assert figures["billed_minor"] == 0
invoice = billing.draft_from_unbilled(db, admin, matter)
billing.approve(db, invoice, admin)
billing.issue(db, invoice, admin)
figures = billing.matter_financials(db, matter)
assert figures["wip_minor"] == 0 # it is billed now, not work in progress
assert figures["billed_minor"] == invoice.gross_minor
assert figures["outstanding_minor"] == invoice.gross_minor
billing.register_payment(db, invoice, amount_minor=invoice.gross_minor)
figures = billing.matter_financials(db, matter)
assert figures["paid_minor"] == invoice.gross_minor
assert figures["outstanding_minor"] == 0
def test_the_firm_summary_only_counts_matters_the_reader_may_see(db, admin, matter):
"""A partner's dashboard must not leak the existence of a walled matter."""
from app.enums import WallMode
from app.services import billing, matters as matters_svc
_time(db, admin, matter, minutes=60)
db.flush()
before = billing.firm_summary(db, admin)["wip_minor"]
matters_svc.set_wall(db, matter, admin, user_id=admin.id, mode=WallMode.deny, reason="t")
db.flush()
after = billing.firm_summary(db, admin)["wip_minor"]
assert after == before - 400_00
matters_svc.clear_wall(db, matter, admin.id)
db.flush()
assert billing.firm_summary(db, admin)["wip_minor"] == before
+167
View File
@@ -0,0 +1,167 @@
"""Court fees and representation costs. DB-free.
Bracket boundaries get the most attention: the statutes read "ponad 500 zł do 1500 zł", so the
upper bound is inclusive, and off-by-one there is the classic way these calculators are wrong.
"""
from __future__ import annotations
import pytest
from app.errors import ValidationError
from app.services import fees
# ── opłata sądowa: art. 13 ust. 1 (fixed brackets) ───────────────────────────
@pytest.mark.parametrize("value_zl,expected_zl", [
(1, 30), (500, 30),
(501, 100), (1_500, 100),
(1_501, 200), (4_000, 200),
(4_001, 400), (7_500, 400),
(7_501, 500), (10_000, 500),
(10_001, 750), (15_000, 750),
(15_001, 1_000), (20_000, 1_000),
])
def test_fixed_brackets_are_upper_inclusive(value_zl, expected_zl):
assert fees.base_court_fee(value_zl * 100)["amount_minor"] == expected_zl * 100
# ── opłata sądowa: art. 13 ust. 2 (5%, cap 200 000 zł) ───────────────────────
def test_above_twenty_thousand_is_five_percent():
assert fees.base_court_fee(20_001_00)["amount_minor"] == 1_001_00 # 5% = 1000,05 → 1001
assert fees.base_court_fee(185_000_00)["amount_minor"] == 9_250_00
assert fees.base_court_fee(1_000_000_00)["amount_minor"] == 50_000_00
def test_proportional_fee_rounds_up_to_a_whole_zloty():
"""art. 21 u.k.s.c. — not a rounding preference. 5% of 20 001 zł is 1000,05 zł."""
result = fees.base_court_fee(20_001_00)
assert result["amount_minor"] % 100 == 0
assert result["amount_minor"] == 1_001_00
def test_proportional_fee_is_capped_and_says_so():
result = fees.base_court_fee(10_000_000_00) # 5% would be 500 000 zł
assert result["amount_minor"] == 200_000_00
assert result["capped"] is True
assert fees.base_court_fee(185_000_00)["capped"] is False
def test_value_must_be_positive_and_sane():
with pytest.raises(ValidationError):
fees.base_court_fee(0)
with pytest.raises(ValidationError):
fees.base_court_fee(-1)
with pytest.raises(ValidationError):
fees.base_court_fee(fees.MAX_VALUE_MINOR + 1)
# ── fractions per kind of filing ─────────────────────────────────────────────
def test_nakazowy_and_epu_are_a_quarter():
"""A quarter of 9250 zł is 2312,50 zł, and art. 21 rounds the payable fee up to 2313 zł —
so the answer is NOT plain integer division of the base fee."""
assert fees.court_fee(185_000_00, "pozew")["amount_minor"] == 9_250_00
assert fees.court_fee(185_000_00, "nakazowy")["amount_minor"] == 2_313_00
assert fees.court_fee(185_000_00, "epu")["amount_minor"] == 2_313_00
def test_zazalenie_is_a_fifth():
assert fees.court_fee(185_000_00, "zazalenie")["amount_minor"] == 1_850_00
def test_fraction_result_is_also_rounded_up_to_a_whole_zloty():
"""A quarter of 30 zł is 7,50 zł — the fee payable is 8 zł, never 7,50."""
quarter = fees.court_fee(500_00, "nakazowy")
assert quarter["amount_minor"] % 100 == 0
assert quarter["amount_minor"] == 8_00
def test_unknown_proceeding_is_rejected():
with pytest.raises(ValidationError):
fees.court_fee(10_000_00, "nieistniejące")
def test_every_result_carries_its_legal_basis():
"""The output is checkable by a lawyer or it is worthless."""
result = fees.court_fee(185_000_00, "epu")
assert "art. 13 ust. 2 u.k.s.c." in result["basis"]
assert "art. 19 ust. 2 pkt 2 u.k.s.c." in result["basis"]
assert "art. 21 u.k.s.c." in result["basis"]
# ── koszty zastępstwa: § 2 rozporządzenia ────────────────────────────────────
@pytest.mark.parametrize("value_zl,expected_zl", [
(500, 90), (501, 270), (1_500, 270),
(1_501, 900), (5_000, 900),
(5_001, 1_800), (10_000, 1_800),
(10_001, 3_600), (50_000, 3_600),
(50_001, 5_400), (200_000, 5_400),
(200_001, 10_800), (2_000_000, 10_800),
(2_000_001, 15_000), (5_000_000, 15_000),
(5_000_001, 25_000), (500_000_000, 25_000),
])
def test_minimum_representation_brackets(value_zl, expected_zl):
assert fees.minimum_representation_fee(value_zl * 100)["amount_minor"] == expected_zl * 100
def test_stage_percentages():
value = 185_000_00 # stawka minimalna 5400 zł
assert fees.representation_costs(value, "i_instancja")["amount_minor"] == 5_400_00
assert fees.representation_costs(value, "apelacja_so")["amount_minor"] == 2_700_00
assert fees.representation_costs(value, "apelacja_sa")["amount_minor"] == 4_050_00
assert fees.representation_costs(value, "kasacja")["amount_minor"] == 4_050_00
assert fees.representation_costs(value, "zazalenie_so")["amount_minor"] == 1_350_00
assert fees.representation_costs(value, "zazalenie_sa")["amount_minor"] == 2_700_00
def test_appeal_before_a_district_court_has_a_floor():
"""§ 10 ust. 1 pkt 1 — 50% of the minimum, but not less than 120 zł."""
assert fees.representation_costs(500_00, "apelacja_so")["amount_minor"] == 120_00
def test_multiplier_is_bounded_by_six_times_the_minimum():
tripled = fees.representation_costs(185_000_00, "i_instancja", multiplier=3)
assert tripled["amount_minor"] == 16_200_00
assert "§ 15 ust. 3" in tripled["basis"]
with pytest.raises(ValidationError):
fees.representation_costs(185_000_00, "i_instancja", multiplier=7)
with pytest.raises(ValidationError):
fees.representation_costs(185_000_00, "i_instancja", multiplier=0)
def test_plain_minimum_does_not_cite_the_uplift():
assert "§ 15 ust. 3" not in fees.representation_costs(185_000_00)["basis"]
# ── the combined estimate ────────────────────────────────────────────────────
def test_estimate_totals_what_the_client_must_find_upfront():
e = fees.estimate(185_000_00, proceeding="pozew", powers_of_attorney=2)
assert e["court_fee"]["amount_minor"] == 9_250_00
assert e["stamp_duty"]["amount_minor"] == 34_00 # 2 × 17 zł
assert e["upfront_minor"] == 9_250_00 + 34_00
# Representation costs are what the OPPONENT may owe us — not an upfront cost.
assert e["representation"]["amount_minor"] == 5_400_00
assert e["upfront_minor"] < e["upfront_minor"] + e["representation"]["amount_minor"]
def test_estimate_can_omit_the_power_of_attorney():
assert fees.estimate(10_000_00, powers_of_attorney=0)["stamp_duty"]["amount_minor"] == 0
with pytest.raises(ValidationError):
fees.estimate(10_000_00, powers_of_attorney=-1)
def test_estimate_ships_its_own_provenance():
"""The numbers have a shelf life, so the payload says which schedule produced them and
tells the reader to check. A calculator that looks authoritative and is out of date is
worse than one that says it might be."""
e = fees.estimate(10_000_00)
assert e["schedule_version"] == fees.SCHEDULE_VERSION
assert "u.k.s.c." in " ".join(e["sources"])
assert e["verify_note"]
def test_options_expose_every_key_the_calculator_accepts():
opts = fees.options()
for item in opts["proceedings"]:
assert fees.court_fee(10_000_00, item["key"])["amount_minor"] > 0
for item in opts["stages"]:
assert fees.representation_costs(10_000_00, item["key"])["amount_minor"] > 0
+404
View File
@@ -0,0 +1,404 @@
"""Full API loop against a migrated + seeded Postgres.
Skipped unless SYGNA_RUN_INTEGRATION=1, matching Galena's convention, so `pytest` stays
DB-free by default and CI runs the real thing.
The flow under test is the one that defines the product: a conflict check that finds a real
hit blocks matter creation until a human decides, and the decision is recorded.
"""
from __future__ import annotations
import datetime as dt
import os
import uuid
import pytest
pytestmark = pytest.mark.skipif(
os.environ.get("SYGNA_RUN_INTEGRATION") != "1",
reason="needs a migrated + seeded Postgres; set SYGNA_RUN_INTEGRATION=1",
)
@pytest.fixture(scope="module")
def client():
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as c:
r = c.post("/api/v1/auth/login", json={
"email": os.environ.get("BOOTSTRAP_ADMIN_EMAIL", "admin@example.com"),
"password": os.environ.get("BOOTSTRAP_ADMIN_PASSWORD", "admin12345"),
})
assert r.status_code == 200, r.text
c.headers["Authorization"] = "Bearer " + r.json()["token"]
yield c
@pytest.fixture(scope="module")
def container(client):
"""Somewhere the admin may open a matter."""
r = client.get("/api/v1/tree/containers")
assert r.status_code == 200, r.text
assert r.json(), "seed should have created at least one container"
return r.json()[0]["id"]
def _unique(prefix: str) -> str:
return f"{prefix} {uuid.uuid4().hex[:8]}"
def test_health(client):
assert client.get("/api/v1/health").json()["status"] == "ok"
def test_clean_check_auto_clears_and_opens_a_matter(client, container):
name = _unique("Testowa Spółka")
party = client.post("/api/v1/parties", json={"kind": "organisation", "name": name}).json()
check = client.post("/api/v1/conflicts", json={"subject": name}).json()
assert check["outcome"] == "clear", check
r = client.post("/api/v1/matters", json={
"name": _unique("Sprawa testowa"), "client_party_id": party["id"],
"parent_node_id": container, "conflict_check_id": check["id"],
})
assert r.status_code == 200, r.text
matter = r.json()
assert matter["reference"].startswith(str(dt.date.today().year))
assert matter["client_name"] == name
def test_a_check_cannot_open_two_matters(client, container):
"""One check, one matter — a `clear` from last month must not open a matter today."""
name = _unique("Jednorazowa")
party = client.post("/api/v1/parties", json={"kind": "organisation", "name": name}).json()
check = client.post("/api/v1/conflicts", json={"subject": name}).json()
body = {"name": _unique("Sprawa"), "client_party_id": party["id"],
"parent_node_id": container, "conflict_check_id": check["id"]}
assert client.post("/api/v1/matters", json=body).status_code == 200
second = client.post("/api/v1/matters", json={**body, "name": _unique("Druga")})
assert second.status_code == 409, second.text
def test_conflict_blocks_then_waiver_unblocks(client, container):
"""The core gate. Acting AGAINST an existing client is found, blocks the matter, and can
only be unblocked by a recorded human decision with a reason."""
client_name = _unique("Alfa Logistyka")
alfa = client.post("/api/v1/parties",
json={"kind": "organisation", "name": client_name}).json()
clear = client.post("/api/v1/conflicts", json={"subject": client_name}).json()
client.post("/api/v1/matters", json={
"name": _unique("Sprawa Alfa"), "client_party_id": alfa["id"],
"parent_node_id": container, "conflict_check_id": clear["id"],
})
# Someone else now wants us to act AGAINST Alfa.
other_name = _unique("Beta Handel")
beta = client.post("/api/v1/parties",
json={"kind": "organisation", "name": other_name}).json()
check = client.post("/api/v1/conflicts",
json={"subject": other_name, "adverse_names": client_name}).json()
assert check["outcome"] == "pending"
assert any(h["kind"] == "client_conflict" for h in check["hits"]), check["hits"]
blocked = client.post("/api/v1/matters", json={
"name": _unique("Sprawa Beta"), "client_party_id": beta["id"],
"parent_node_id": container, "conflict_check_id": check["id"],
})
assert blocked.status_code == 409, blocked.text
# A waiver needs a reason.
assert client.post(f"/api/v1/conflicts/{check['id']}/decide",
json={"outcome": "waived"}).status_code == 422
decided = client.post(f"/api/v1/conflicts/{check['id']}/decide", json={
"outcome": "waived", "note": "Zgoda obu klientów na piśmie; wdrożono chiński mur.",
})
assert decided.status_code == 200, decided.text
# Decided checks are immutable.
assert client.post(f"/api/v1/conflicts/{check['id']}/decide",
json={"outcome": "clear", "note": "x"}).status_code == 409
ok = client.post("/api/v1/matters", json={
"name": _unique("Sprawa Beta"), "client_party_id": beta["id"],
"parent_node_id": container, "conflict_check_id": check["id"],
})
assert ok.status_code == 200, ok.text
def test_declined_check_can_never_open_a_matter(client, container):
name = _unique("Odmowa")
party = client.post("/api/v1/parties", json={"kind": "organisation", "name": name}).json()
check = client.post("/api/v1/conflicts",
json={"subject": name, "adverse_names": name}).json()
if check["outcome"] == "pending":
client.post(f"/api/v1/conflicts/{check['id']}/decide",
json={"outcome": "declined", "note": "Nie prowadzimy."})
r = client.post("/api/v1/matters", json={
"name": _unique("Sprawa"), "client_party_id": party["id"],
"parent_node_id": container, "conflict_check_id": check["id"],
})
assert r.status_code == 409, r.text
def _open_matter(client, container, label="Sprawa"):
name = _unique(label + " klient")
party = client.post("/api/v1/parties", json={"kind": "organisation", "name": name}).json()
check = client.post("/api/v1/conflicts", json={"subject": name}).json()
return client.post("/api/v1/matters", json={
"name": _unique(label), "client_party_id": party["id"],
"parent_node_id": container, "conflict_check_id": check["id"],
}).json()
def test_derived_deadline_records_its_basis(client, container):
matter = _open_matter(client, container, "Termin")
service = dt.date.today() - dt.timedelta(days=3)
r = client.post(f"/api/v1/matters/{matter['id']}/deadlines/derive", json={
"title": "Odpowiedź na sprzeciw", "kind": "procedural", "source": "court",
"service_date": service.isoformat(), "days": 14,
})
assert r.status_code == 200, r.text
d = r.json()
assert d["due_date"] == (service + dt.timedelta(days=14)).isoformat()
assert service.isoformat() in d["basis"] and "14" in d["basis"]
def test_dual_control_refuses_the_creator(client, container):
"""A four-eyes check performed by one pair of eyes is theatre."""
matter = _open_matter(client, container, "Dual")
d = client.post(f"/api/v1/matters/{matter['id']}/deadlines", json={
"title": "Przedawnienie", "kind": "limitation", "source": "statute",
"due_date": (dt.date.today() + dt.timedelta(days=30)).isoformat(),
}).json()
r = client.post(f"/api/v1/deadlines/{d['id']}/confirm")
assert r.status_code == 409, r.text
def test_internal_deadlines_need_no_second_pair_of_eyes(client, container):
matter = _open_matter(client, container, "Internal")
d = client.post(f"/api/v1/matters/{matter['id']}/deadlines", json={
"title": "Zadzwonić do klienta", "kind": "internal", "source": "internal",
"due_date": (dt.date.today() + dt.timedelta(days=2)).isoformat(),
}).json()
assert client.post(f"/api/v1/deadlines/{d['id']}/confirm").status_code == 200
def test_time_rounds_up_and_values_at_the_matter_rate(client, container):
matter = _open_matter(client, container, "Czas")
client.patch(f"/api/v1/matters/{matter['id']}", json={"default_rate_minor": 45000})
r = client.post(f"/api/v1/matters/{matter['id']}/time", json={
"duration": "1:31", "narrative": "Analiza akt.",
})
assert r.status_code == 200, r.text
entry = r.json()
assert entry["minutes"] == 96 # 91 → next 6-minute unit
assert entry["amount_minor"] == 72000 # 96 * 45000 // 60
def test_time_narrative_is_required(client, container):
matter = _open_matter(client, container, "Pusty")
r = client.post(f"/api/v1/matters/{matter['id']}/time",
json={"duration": "1h", "narrative": " "})
assert r.status_code == 422, r.text
def test_ethical_wall_hides_the_matter_from_an_admin(client, container):
"""A wall that a partner or an administrator can walk through is not a wall. The admin
here is the only user in the test session, so denying them proves the rule."""
matter = _open_matter(client, container, "Mur")
me = client.get("/api/v1/auth/me").json()
assert client.get(f"/api/v1/matters/{matter['id']}").status_code == 200
client.post(f"/api/v1/matters/{matter['id']}/walls", json={
"user_id": me["id"], "mode": "deny", "reason": "test",
})
# 404, not 403 — the existence of a matter is itself privileged.
assert client.get(f"/api/v1/matters/{matter['id']}").status_code == 404
listed = client.get("/api/v1/matters").json()
assert all(m["id"] != matter["id"] for m in listed)
# The barrier is administered from OUTSIDE it (manager on the parent department), so
# walling yourself off is never a one-way door.
assert client.get(f"/api/v1/matters/{matter['id']}/walls").status_code == 200
assert client.delete(f"/api/v1/matters/{matter['id']}/walls/{me['id']}").status_code == 200
assert client.get(f"/api/v1/matters/{matter['id']}").status_code == 200
def test_matter_node_is_a_leaf(client, container):
"""Mirrors Galena's project rule: nothing may be created inside a matter."""
matter = _open_matter(client, container, "Liść")
detail = client.get(f"/api/v1/matters/{matter['id']}").json()
r = client.post("/api/v1/nodes", json={
"parent_id": detail["matter"]["node_id"], "kind": "folder", "name": "podfolder",
})
assert r.status_code == 409, r.text
def test_nodes_router_refuses_to_create_a_matter(client, container):
r = client.post("/api/v1/nodes",
json={"parent_id": container, "kind": "matter", "name": "obejście"})
assert r.status_code == 409, r.text
def test_sygna_never_creates_a_galena_project(client, container):
r = client.post("/api/v1/nodes",
json={"parent_id": container, "kind": "project", "name": "projekt"})
assert r.status_code == 409, r.text
# ── correspondence: the chain from a service date to a deadline ──────────────
def _record(client, **kw):
body = {"channel": "court_portal", "subject": _unique("Pismo"), **kw}
r = client.post("/api/v1/correspondence", json=body)
assert r.status_code == 200, r.text
return r.json()
def test_new_correspondence_lands_unassigned_in_the_inbox(client):
item = _record(client)
assert item["status"] == "unassigned"
assert item["matter_id"] is None
inbox = client.get("/api/v1/correspondence/inbox").json()
assert any(i["id"] == item["id"] for i in inbox["items"])
def test_external_ref_makes_ingestion_idempotent(client):
"""A connector that re-polls must not create the item twice."""
ref = "EPO-" + uuid.uuid4().hex[:10]
_record(client, external_ref=ref)
dup = client.post("/api/v1/correspondence",
json={"channel": "court_portal", "subject": "znowu", "external_ref": ref})
assert dup.status_code == 409, dup.text
# A different channel with the same ref is a different item — the index is per channel.
assert client.post("/api/v1/correspondence",
json={"channel": "edoreczenia", "subject": "inny kanał",
"external_ref": ref}).status_code == 200
def test_undated_authoritative_post_is_surfaced_separately(client):
"""An e-Doręczenia item with no service date is a clock that may already be running."""
before = client.get("/api/v1/correspondence/inbox").json()["undated_total"]
item = _record(client, channel="edoreczenia")
assert item["legal_service_date"] is None
inbox = client.get("/api/v1/correspondence/inbox").json()
assert inbox["undated_total"] == before + 1
assert client.get("/api/v1/dashboard").json()["cards"]["undated_service"] == before + 1
# The list is oldest-first and paged, so assert the contract (the total) rather than the
# newest row's presence — that assertion would pass or fail depending on how full the
# inbox happens to be, which is exactly the bug this endpoint used to have.
assert len(inbox["undated"]) <= inbox["limit"]
assert len(inbox["undated"]) == min(inbox["undated_total"], inbox["limit"])
def test_inbox_reports_a_true_total_alongside_a_paged_list(client):
"""A truncated list whose length is shown as the count reads as 'this is everything'."""
small = client.get("/api/v1/correspondence/inbox?limit=1").json()
assert len(small["items"]) <= 1
assert small["items_total"] >= len(small["items"])
full = client.get("/api/v1/correspondence/inbox").json()
assert full["items_total"] == small["items_total"]
def test_service_date_cannot_be_in_the_future(client):
tomorrow = (dt.date.today() + dt.timedelta(days=1)).isoformat()
r = client.post("/api/v1/correspondence",
json={"channel": "post", "subject": "z przyszłości",
"legal_service_date": tomorrow})
assert r.status_code == 422, r.text
def test_deadline_derived_from_correspondence_points_back_at_it(client, container):
matter = _open_matter(client, container, "Korespondencja")
service = dt.date.today() - dt.timedelta(days=2)
item = _record(client, legal_service_date=service.isoformat())
client.post(f"/api/v1/correspondence/{item['id']}/assign",
json={"matter_id": matter["id"]})
r = client.post(f"/api/v1/correspondence/{item['id']}/deadlines", json={
"title": "Odpowiedź na sprzeciw", "kind": "procedural", "source": "court", "days": 14,
})
assert r.status_code == 200, r.text
d = r.json()
assert d["due_date"] == (service + dt.timedelta(days=14)).isoformat()
assert service.isoformat() in d["basis"]
detail = client.get(f"/api/v1/correspondence/{item['id']}").json()
assert detail["item"]["derived_deadlines"] == 1
assert detail["deadlines"][0]["id"] == d["id"]
def test_deriving_needs_a_matter_and_a_service_date(client, container):
matter = _open_matter(client, container, "Braki")
body = {"title": "X", "kind": "procedural", "source": "court", "days": 7}
unassigned = _record(client, legal_service_date=dt.date.today().isoformat())
assert client.post(f"/api/v1/correspondence/{unassigned['id']}/deadlines",
json=body).status_code == 409
undated = _record(client)
client.post(f"/api/v1/correspondence/{undated['id']}/assign",
json={"matter_id": matter["id"]})
assert client.post(f"/api/v1/correspondence/{undated['id']}/deadlines",
json=body).status_code == 409
def test_service_date_is_correctable_until_a_deadline_depends_on_it(client, container):
"""Silently moving a date that six deadlines were computed from is how a firm misses all
six — so the correction is refused, loudly, rather than cascading."""
matter = _open_matter(client, container, "Data")
item = _record(client, legal_service_date=(dt.date.today() - dt.timedelta(days=5)).isoformat())
client.post(f"/api/v1/correspondence/{item['id']}/assign", json={"matter_id": matter["id"]})
corrected = (dt.date.today() - dt.timedelta(days=4)).isoformat()
ok = client.put(f"/api/v1/correspondence/{item['id']}/service-date",
json={"legal_service_date": corrected})
assert ok.status_code == 200, ok.text
assert ok.json()["legal_service_date"] == corrected
client.post(f"/api/v1/correspondence/{item['id']}/deadlines", json={
"title": "Zażalenie", "kind": "procedural", "source": "court", "days": 7,
})
blocked = client.put(f"/api/v1/correspondence/{item['id']}/service-date", json={
"legal_service_date": (dt.date.today() - dt.timedelta(days=3)).isoformat(),
})
assert blocked.status_code == 409, blocked.text
def test_correspondence_with_derived_deadlines_cannot_be_deleted(client, container):
"""A deadline that has lost the document proving where its date came from is worse than
one that blocks a delete."""
matter = _open_matter(client, container, "Usuwanie")
item = _record(client, legal_service_date=dt.date.today().isoformat())
client.post(f"/api/v1/correspondence/{item['id']}/assign", json={"matter_id": matter["id"]})
assert client.delete(f"/api/v1/correspondence/{item['id']}").status_code == 200
item2 = _record(client, legal_service_date=dt.date.today().isoformat())
client.post(f"/api/v1/correspondence/{item2['id']}/assign", json={"matter_id": matter["id"]})
client.post(f"/api/v1/correspondence/{item2['id']}/deadlines", json={
"title": "Apelacja", "kind": "procedural", "source": "court", "days": 14,
})
assert client.delete(f"/api/v1/correspondence/{item2['id']}").status_code == 409
assert client.post(f"/api/v1/correspondence/{item2['id']}/unassign").status_code == 409
def test_walled_matter_hides_its_correspondence(client, container):
matter = _open_matter(client, container, "MurKor")
me = client.get("/api/v1/auth/me").json()
item = _record(client, legal_service_date=dt.date.today().isoformat())
client.post(f"/api/v1/correspondence/{item['id']}/assign", json={"matter_id": matter["id"]})
client.post(f"/api/v1/matters/{matter['id']}/walls",
json={"user_id": me["id"], "mode": "deny", "reason": "test"})
assert client.get(f"/api/v1/correspondence/{item['id']}").status_code == 404
assert client.get(f"/api/v1/matters/{matter['id']}/correspondence").status_code == 404
client.delete(f"/api/v1/matters/{matter['id']}/walls/{me['id']}")
def test_audit_log_records_the_matter_opening(client, container):
matter = _open_matter(client, container, "Audyt")
rows = client.get("/api/v1/activity").json()
assert any(r["action"] == "matter.open" and r["entity_id"] == matter["id"] for r in rows)

Some files were not shown because too many files have changed in this diff Show More