Initial backend: FastAPI + Postgres FTS + questionnaire engine + RBAC + OTel/HyperDX/ClickHouse
Self-hosted single-tenant backend for the Counsel Scorecard law-firm scoring platform. - FastAPI + SQLAlchemy 2 + Alembic on PostgreSQL 16 (20 tables, native enums) - Generic questionnaire engine (question / answer_option / questionnaire / response / response_revision history) generalizing the spec's criterion/evaluation model - PostgreSQL FTS: generated tsvector columns + GIN indexes + pg_trgm fuzzy fallback - RBAC (admin/legal_ops/matter_owner/viewer) with DB-backed sessions + append-only audit_log - present_i composite scoring with immutable per-cycle score_snapshot - Observability: OTel Collector -> ClickHouse -> HyperDX (opt-in) - Least-privilege DB roles, Docker Compose, Caddy reverse proxy Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
# Copy to .env and replace every "change_me_*" value before running.
|
||||
# .env is git-ignored. Keep passwords alphanumeric (the DB init scripts
|
||||
# interpolate them into SQL literals).
|
||||
|
||||
# ─── PostgreSQL ──────────────────────────────────────────────────────────────
|
||||
POSTGRES_DB=scoring
|
||||
DB_SUPERUSER_PASSWORD=change_me_super
|
||||
DB_APP_PASSWORD=change_me_app
|
||||
DB_MIGRATOR_PASSWORD=change_me_migrator
|
||||
|
||||
# Runtime (least-privilege "app" role: DML only) and migrations ("migrator": DDL).
|
||||
# Inside docker the host is "postgres"; for a local run use "localhost".
|
||||
DATABASE_URL=postgresql+psycopg://app:change_me_app@postgres:5432/scoring
|
||||
MIGRATION_DATABASE_URL=postgresql+psycopg://migrator:change_me_migrator@postgres:5432/scoring
|
||||
|
||||
# ─── Application ─────────────────────────────────────────────────────────────
|
||||
APP_ENV=production
|
||||
# Generate with: python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
SECRET_KEY=change_me_to_a_long_random_string
|
||||
SESSION_TTL_HOURS=12
|
||||
BASE_CURRENCY=EUR
|
||||
|
||||
# First admin, created idempotently by the seed step.
|
||||
BOOTSTRAP_ADMIN_EMAIL=admin@example.com
|
||||
BOOTSTRAP_ADMIN_PASSWORD=change_me_admin
|
||||
|
||||
# ─── OpenTelemetry (backend → OTel Collector) ────────────────────────────────
|
||||
# Leave disabled to run the backend alone. Set true when the observability
|
||||
# stack (docker-compose.observability.yml) is up.
|
||||
OTEL_ENABLED=false
|
||||
OTEL_SERVICE_NAME=counsel-scorecard-backend
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL=grpc
|
||||
|
||||
# ─── ClickHouse (observability store, used by OTel Collector + HyperDX) ───────
|
||||
CLICKHOUSE_USER=otel
|
||||
CLICKHOUSE_PASSWORD=change_me_clickhouse
|
||||
CLICKHOUSE_DB=otel
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
# Secrets / local env
|
||||
.env
|
||||
*.env
|
||||
!.env.example
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
|
||||
# Build / dist
|
||||
dist/
|
||||
build/
|
||||
*.log
|
||||
|
||||
# Docker / data
|
||||
pgdata/
|
||||
uploads/
|
||||
|
||||
# Editor
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
.DS_Store
|
||||
@@ -0,0 +1,32 @@
|
||||
# Reverse proxy for the Counsel Scorecard backend.
|
||||
#
|
||||
# Replace ":80" with your domain (e.g. "scorecard.example.com") to get
|
||||
# automatic Let's Encrypt TLS. For an internal network without public DNS,
|
||||
# use: scorecard.internal { tls internal ... }
|
||||
#
|
||||
# Caddy is the ONLY service published to the host. The backend is reachable
|
||||
# solely on the private docker network.
|
||||
|
||||
{
|
||||
admin off
|
||||
}
|
||||
|
||||
:80 {
|
||||
encode gzip
|
||||
|
||||
header {
|
||||
X-Content-Type-Options nosniff
|
||||
X-Frame-Options DENY
|
||||
Referrer-Policy no-referrer
|
||||
-Server
|
||||
}
|
||||
|
||||
# Public API surface.
|
||||
reverse_proxy /api/* backend:8000
|
||||
|
||||
# Liveness for load balancers (kept minimal — no version leak).
|
||||
respond /healthz 200
|
||||
|
||||
# Everything else (a SPA would be served here from ./frontend/dist).
|
||||
respond 404
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
# Counsel Scorecard — Backend
|
||||
|
||||
> Self-hosted, single-tenant backend for scoring external law firms ("counsel") for an
|
||||
> in-house legal department. After a matter closes, an in-house lawyer fills in a structured
|
||||
> **questionnaire**; each quarter a **review cycle** rolls those responses into an immutable,
|
||||
> explainable composite score per firm — turning relationship-based panel management into a
|
||||
> measurable, auditable, defensible process.
|
||||
|
||||
**License:** Apache-2.0 · **Status:** MVP-0 (qualitative core loop) · **Frontend:** out of scope (this repo is the backend only)
|
||||
|
||||
Built from the product/architecture spec in `../Counsel-Scorecard/`.
|
||||
|
||||
---
|
||||
|
||||
## Contents
|
||||
|
||||
- [Highlights](#highlights)
|
||||
- [Tech stack](#tech-stack)
|
||||
- [Architecture](#architecture)
|
||||
- [Data model](#data-model)
|
||||
- [Quick start](#quick-start)
|
||||
- [Observability stack](#observability-stack)
|
||||
- [Configuration](#configuration)
|
||||
- [RBAC](#rbac)
|
||||
- [API reference](#api-reference)
|
||||
- [Scoring model](#scoring-model)
|
||||
- [Local development](#local-development)
|
||||
- [Project layout](#project-layout)
|
||||
- [Scope & roadmap](#scope--roadmap)
|
||||
- [Security](#security)
|
||||
|
||||
---
|
||||
|
||||
## Highlights
|
||||
|
||||
| Requirement | How it's delivered |
|
||||
|---|---|
|
||||
| **PostgreSQL + Full-Text Search** | PostgreSQL 16 with generated `tsvector` columns + **GIN** indexes on `firm`, `matter`, `question`, `response`; `pg_trgm` trigram fuzzy fallback; one `GET /api/v1/search` endpoint. |
|
||||
| **Generic questionnaire engine** | `question` → `answer_option` (possible answers) → `questionnaire` + `questionnaire_question` (grouped, weighted set) → `response` → `response_item` → `response_revision` (**append-only history**). Questions/answers/weights are data, not code. |
|
||||
| **Role controls (RBAC)** | `user_role` enum (`admin` / `legal_ops` / `matter_owner` / `viewer`), enforced by `require_role(...)` dependencies. Server-side sessions give an instant kill-switch. |
|
||||
| **Observability** | OpenTelemetry SDK → **OTel Collector** → **ClickHouse** → **HyperDX** unified UI (metrics + logs + traces on one screen). Opt-in. |
|
||||
| **Audit & least-privilege** | Append-only `audit_log` (runtime role has no `UPDATE`/`DELETE`); separate `migrator` (DDL) and `app` (DML-only) DB roles; Postgres never published to the host. |
|
||||
|
||||
---
|
||||
|
||||
## Tech stack
|
||||
|
||||
| Layer | Choice | License |
|
||||
|---|---|---|
|
||||
| Language / runtime | Python 3.12 | PSF |
|
||||
| Web framework | FastAPI | MIT |
|
||||
| ORM / migrations | SQLAlchemy 2 + Alembic | MIT |
|
||||
| DB driver | psycopg 3 | LGPL + linking exception |
|
||||
| Database | PostgreSQL 16 | PostgreSQL |
|
||||
| Search | Postgres FTS (`tsvector` + GIN + `pg_trgm`) | PostgreSQL |
|
||||
| Passwords | Argon2id (`argon2-cffi`) | MIT |
|
||||
| Instrumentation | OpenTelemetry (OTLP/gRPC) | Apache-2.0 |
|
||||
| Observability store / UI | ClickHouse + HyperDX | Apache-2.0 / MIT |
|
||||
| Reverse proxy | Caddy | Apache-2.0 |
|
||||
| Orchestration | Docker Compose | Apache-2.0 |
|
||||
|
||||
Every dependency is permissive (Apache / MIT / PostgreSQL) — no GPL/AGPL/source-available, so it clears a corporate legal/IT license scan.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Internet / LAN
|
||||
│ :443 (HTTPS, the only published port)
|
||||
┌────▼────┐
|
||||
│ Caddy │ reverse proxy, TLS, security headers
|
||||
└────┬────┘
|
||||
│ /api/v1/*
|
||||
┌───────▼────────┐ private docker network
|
||||
│ FastAPI backend │──────────────┐
|
||||
│ routers→services│ │ OTLP/gRPC (opt-in)
|
||||
│ →models (ORM) │ ▼
|
||||
└───────┬─────────┘ ┌──────────────────┐ ┌────────────┐
|
||||
│ │ OTel Collector │──▶│ ClickHouse │◀── HyperDX (UI :8080)
|
||||
┌────────▼─────────┐ └──────────────────┘ └────────────┘
|
||||
│ PostgreSQL 16 │ (expose only, never published)
|
||||
└──────────────────┘
|
||||
```
|
||||
|
||||
Strict one-way layering (spec §I.1) — each layer depends only on the one below:
|
||||
|
||||
```
|
||||
routers/ HTTP, Pydantic validation, auth + RBAC · never touches the DB session
|
||||
services/ domain logic: scoring, responses, audit · never builds raw SQL
|
||||
models/ ORM entities, constraints, indexes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Data model
|
||||
|
||||
20 tables. The questionnaire engine generalizes the spec's hardcoded `criterion`/`evaluation`
|
||||
tables; the domain tables ground it in the Counsel Scorecard problem.
|
||||
|
||||
```
|
||||
Questionnaire engine Domain
|
||||
──────────────────── ──────
|
||||
question ──1:N── answer_option firm ──1:N── office
|
||||
│ │
|
||||
questionnaire ─N:M(weight)─ question ├─N:M── practice_area
|
||||
│ └─N:M── jurisdiction
|
||||
response ──N:1── questionnaire matter ──N:1── firm / practice_area / jurisdiction / app_user
|
||||
├──1:N── response_item ──N:1── question
|
||||
└──1:N── response_revision (append-only history) review_cycle ──1:N── score_snapshot ──N:1── firm
|
||||
|
||||
Identity & ops: app_user · session · app_setting · audit_log
|
||||
```
|
||||
|
||||
| Your request | Table(s) | Generalizes (spec) |
|
||||
|---|---|---|
|
||||
| questions | `question` | `criterion` |
|
||||
| possible answers | `answer_option` | the 1–5 scale anchors |
|
||||
| grouped questionnaire set | `questionnaire` + `questionnaire_question` | evaluation form + `criterion_weight` |
|
||||
| results with history | `response` + `response_item` + `response_revision` | `evaluation` + `evaluation_score` |
|
||||
|
||||
The seed loads the canonical 8 criteria — 5 qualitative (1–5 scale with anchors) + 3
|
||||
quantitative — into a default `counsel_evaluation` questionnaire whose weights sum to 1.0.
|
||||
|
||||
---
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cp .env.example .env # edit every change_me_* value
|
||||
docker compose up -d --build # postgres → migrate (+seed) → backend → caddy
|
||||
```
|
||||
|
||||
- API: `http://localhost/api/v1` — interactive docs at **`/api/v1/docs`**.
|
||||
- Log in with the bootstrap admin from `.env`:
|
||||
|
||||
```bash
|
||||
curl -s -X POST localhost/api/v1/auth/login \
|
||||
-H 'content-type: application/json' \
|
||||
-d '{"email":"admin@example.com","password":"<BOOTSTRAP_ADMIN_PASSWORD>"}'
|
||||
# → sets an HttpOnly session cookie and returns a bearer token for scripting
|
||||
```
|
||||
|
||||
A first end-to-end flow: `POST /firms` → `POST /matters` → `POST /responses` (as a
|
||||
`matter_owner`) → `POST /review-cycles/{id}/close` → `GET /review-cycles/{id}/snapshots`.
|
||||
|
||||
---
|
||||
|
||||
## Observability stack
|
||||
|
||||
Bring it up alongside the app and set `OTEL_ENABLED=true` in `.env`:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.yml -f docker-compose.observability.yml up -d --build
|
||||
```
|
||||
|
||||
- **HyperDX UI:** `http://localhost:8080`. On first launch add a ClickHouse source pointing
|
||||
at `clickhouse:8123` (database `otel`, tables `otel_traces` / `otel_logs` / `otel_metrics`).
|
||||
- The bundled **MongoDB** is HyperDX's own metadata store — it holds no scorecard data.
|
||||
- The `DEFAULT_CONNECTIONS` env can pre-seed that source, but its exact shape varies by
|
||||
HyperDX version — verify against your pinned image.
|
||||
|
||||
> **Lighter alternative:** replace the four services with the single bundled image
|
||||
> `hyperdx/hyperdx-all-in-one` (OTLP on 4317/4318, UI on 8080) — zero config, at the cost of
|
||||
> not seeing the components separately.
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
All via `.env` (copy from `.env.example`; it's git-ignored). Keys you'll set:
|
||||
|
||||
| Variable | Purpose |
|
||||
|---|---|
|
||||
| `POSTGRES_DB`, `DB_SUPERUSER_PASSWORD` | Postgres bootstrap |
|
||||
| `DB_APP_PASSWORD`, `DB_MIGRATOR_PASSWORD` | least-privilege role passwords |
|
||||
| `DATABASE_URL` | runtime connection (`app` role, DML-only) |
|
||||
| `MIGRATION_DATABASE_URL` | migrations + seed (`migrator` role, DDL) |
|
||||
| `APP_ENV` | `production` enables Secure cookies, hides stack traces |
|
||||
| `SECRET_KEY` | app secret — `python -c "import secrets;print(secrets.token_urlsafe(48))"` |
|
||||
| `SESSION_TTL_HOURS` | session lifetime |
|
||||
| `BASE_CURRENCY` | instance base currency (stored in `app_setting`) |
|
||||
| `BOOTSTRAP_ADMIN_EMAIL` / `_PASSWORD` | first admin, created idempotently by the seed |
|
||||
| `OTEL_ENABLED` | turn OTLP export on/off (off → backend runs standalone) |
|
||||
| `OTEL_EXPORTER_OTLP_ENDPOINT` | collector address (`http://otel-collector:4317`) |
|
||||
| `CLICKHOUSE_USER` / `_PASSWORD` / `_DB` | ClickHouse credentials for collector + HyperDX |
|
||||
|
||||
---
|
||||
|
||||
## RBAC
|
||||
|
||||
| Action | admin | legal_ops | matter_owner | viewer |
|
||||
|---|:--:|:--:|:--:|:--:|
|
||||
| Manage users / roles | ✅ | — | — | — |
|
||||
| Configure questions / questionnaires / weights | ✅ | ✅ | — | — |
|
||||
| CRUD firms | ✅ | ✅ | — | — |
|
||||
| CRUD matters | ✅ | ✅ | own only | — |
|
||||
| Submit response (evaluation) | — | — | ✅ own matter | — |
|
||||
| Open / close review cycle | ✅ | ✅ | — | — |
|
||||
| Read rankings / snapshots | ✅ | ✅ | own + aggregate | ✅ aggregate |
|
||||
| Read audit log | ✅ | ✅ | — | — |
|
||||
|
||||
`admin`/`legal_ops` deliberately **cannot** submit evaluations — separation of duties protects the independence of the matter owner's assessment.
|
||||
|
||||
---
|
||||
|
||||
## API reference
|
||||
|
||||
Base path `/api/v1`. Full schema at `/api/v1/docs` (OpenAPI).
|
||||
|
||||
```
|
||||
Auth POST /auth/login · POST /auth/logout · GET /auth/me
|
||||
Users GET/POST /users · PATCH /users/{id} · POST /users/{id}/deactivate
|
||||
Firms GET/POST /firms · GET/PATCH /firms/{id}
|
||||
Matters GET/POST /matters · GET /matters/{id}
|
||||
Questions GET/POST /questions · GET /questions/{id}
|
||||
Questionnaires GET/POST /questionnaires · GET /questionnaires/{id}
|
||||
Responses POST /responses · GET /responses/{id} · GET /responses/{id}/history
|
||||
Review cycles GET/POST /review-cycles · POST /review-cycles/{id}/close · GET /review-cycles/{id}/snapshots
|
||||
Search GET /search?q=...&types=firm,matter,question,response
|
||||
Health GET /health
|
||||
```
|
||||
|
||||
Errors use RFC 9457 Problem Details (`application/problem+json`).
|
||||
|
||||
---
|
||||
|
||||
## Scoring model
|
||||
|
||||
Composite score is the spec's `present_i` weighted mean (§F.3):
|
||||
|
||||
```
|
||||
Σ (wᵢ · Cᵢ · presentᵢ)
|
||||
score = ───────────────────────── × 20
|
||||
Σ (wᵢ · presentᵢ)
|
||||
```
|
||||
|
||||
- `Cᵢ` — criterion value on the 1–5 scale (the cross-response average for a firm in a cycle)
|
||||
- `wᵢ` — configurable weight per question
|
||||
- `presentᵢ` — 1 if the criterion has data, else 0; re-normalizing the denominator so missing
|
||||
data (e.g. the quantitative criteria in MVP-0) neither imputes zero nor penalizes a firm
|
||||
- `× 20` — rescales 1–5 → 0–100
|
||||
|
||||
Constrained-choice evaluations are excluded from the ranking composite (fairness). Each
|
||||
closed cycle materializes one **immutable** `score_snapshot` per firm, with a full
|
||||
per-criterion `breakdown` for audit.
|
||||
|
||||
---
|
||||
|
||||
## Local development
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Point DATABASE_URL / MIGRATION_DATABASE_URL at a local Postgres 16 (with pg_trgm).
|
||||
alembic upgrade head && python -m app.seed
|
||||
uvicorn app.main:app --reload --port 8000
|
||||
|
||||
pytest # DB-free smoke tests
|
||||
alembic upgrade head --sql # inspect the full generated DDL without a DB
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Project layout
|
||||
|
||||
```
|
||||
.
|
||||
├── docker-compose.yml app stack (postgres · migrate · backend · caddy)
|
||||
├── docker-compose.observability.yml OTel Collector · ClickHouse · HyperDX · Mongo
|
||||
├── Caddyfile reverse proxy
|
||||
├── .env.example configuration template
|
||||
├── db/init/ extensions + least-privilege roles (run as superuser)
|
||||
├── observability/ otel-collector-config.yaml
|
||||
└── backend/
|
||||
├── Dockerfile · requirements.txt · pyproject.toml · alembic.ini
|
||||
├── alembic/ env + initial migration (enums, tables, FTS, grants)
|
||||
└── app/
|
||||
├── main.py config.py db.py deps.py errors.py security.py observability.py
|
||||
├── enums.py schemas.py seed.py logging_config.py
|
||||
├── models/ ORM entities (identity, reference, firm, matter, review, questionnaire)
|
||||
├── services/ auth, responses, scoring, search, audit
|
||||
└── routers/ auth, users, firms, matters, questions, questionnaires,
|
||||
responses, review_cycles, search, health
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Scope & roadmap
|
||||
|
||||
- **In this build (MVP-0):** questionnaire engine, RBAC, Postgres FTS, `present_i` scoring,
|
||||
review cycles + immutable snapshots, append-only audit, observability.
|
||||
- **Modeled but not built (roadmap):** invoice import (CSV/PDF) and the 3 quantitative
|
||||
criteria, multi-currency with frozen FX, recency weighting, SSO/OIDC, AI scrutiny. The
|
||||
scoring formula already tolerates their absence via `present_i` re-normalization.
|
||||
|
||||
---
|
||||
|
||||
## Security
|
||||
|
||||
- Secrets only in `.env` (git-ignored); passwords hashed with **Argon2id**.
|
||||
- Postgres uses `expose`, never `ports`; Caddy is the only host-published service.
|
||||
- Server-side sessions (`session` table) → logout / deactivate revokes access instantly.
|
||||
- `app` DB role is DML-only and append-only on `audit_log`; DDL is isolated to `migrator`.
|
||||
- For production: terminate TLS at Caddy with your domain and rate-limit `/auth` (Caddy plugin), per spec §K.
|
||||
@@ -0,0 +1,11 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
.env
|
||||
*.env
|
||||
tests/
|
||||
*.md
|
||||
@@ -0,0 +1,28 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PIP_NO_CACHE_DIR=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# System deps: libpq for psycopg, curl for debugging. Kept minimal.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends libpq5 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
# Run as non-root.
|
||||
RUN useradd --create-home --uid 10001 appuser \
|
||||
&& mkdir -p /data/uploads \
|
||||
&& chown -R appuser:appuser /app /data
|
||||
USER appuser
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -0,0 +1,40 @@
|
||||
# Alembic config. The DB URL is injected at runtime from MIGRATION_DATABASE_URL
|
||||
# (the least-privilege "migrator" role) inside alembic/env.py — never hard-coded here.
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
prepend_sys_path = .
|
||||
path_separator = os
|
||||
|
||||
[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
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Alembic environment. URL comes from MIGRATION_DATABASE_URL (the migrator role)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from app.config import get_settings
|
||||
from app.models import Base # noqa: F401 — populates Base.metadata
|
||||
|
||||
config = context.config
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
settings = get_settings()
|
||||
config.set_main_option("sqlalchemy.url", settings.migration_database_url)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(
|
||||
url=settings.migration_database_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,
|
||||
compare_type=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
"""
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: str | None = ${repr(down_revision)}
|
||||
branch_labels: str | Sequence[str] | None = ${repr(branch_labels)}
|
||||
depends_on: str | Sequence[str] | None = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,72 @@
|
||||
"""initial schema — enums, tables, FTS columns/indexes, audit_log lockdown
|
||||
|
||||
Revision ID: 0001_initial
|
||||
Revises:
|
||||
Create Date: 2026-06-09
|
||||
|
||||
Strategy: create the native PG enum types explicitly (the ORM declares them with
|
||||
create_type=False), then build every table/index/generated-column from the ORM
|
||||
metadata, then enforce append-only audit_log for the runtime `app` role.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
|
||||
from app.models import Base
|
||||
|
||||
revision: str = "0001_initial"
|
||||
down_revision: str | None = None
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
# name → ordered enum labels (spec §H.3). Must exist before metadata.create_all().
|
||||
ENUMS: dict[str, list[str]] = {
|
||||
"user_role": ["admin", "legal_ops", "matter_owner", "viewer"],
|
||||
"firm_status": ["active", "inactive", "blacklisted"],
|
||||
"matter_status": ["open", "in_progress", "closed", "cancelled"],
|
||||
"matter_type": ["transactional", "advisory", "litigation", "regulatory", "dispute"],
|
||||
"complexity_band": ["routine", "standard", "complex", "bet_the_company"],
|
||||
"value_band": ["lt_50k", "50k_250k", "250k_1m", "1m_10m", "gt_10m"],
|
||||
"constrained_reason": [
|
||||
"regulator", "counterparty", "sole_qualified", "client_mandated", "other",
|
||||
],
|
||||
"review_cycle_status": ["open", "closed"],
|
||||
"firm_ranking_status": [
|
||||
"provisional", "at_risk", "watch", "solid", "top_performer", "remove_candidate",
|
||||
],
|
||||
"question_category": ["qualitative", "quantitative"],
|
||||
"answer_type": ["scale", "single_choice", "multi_choice", "boolean", "numeric", "text"],
|
||||
"questionnaire_status": ["draft", "active", "archived"],
|
||||
"response_status": ["draft", "submitted", "locked"],
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
|
||||
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)
|
||||
|
||||
# audit_log is append-only: the runtime role may INSERT/SELECT, never UPDATE/DELETE.
|
||||
op.execute(
|
||||
"""
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'app') THEN
|
||||
REVOKE UPDATE, DELETE ON audit_log FROM app;
|
||||
END IF;
|
||||
END $$;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
Base.metadata.drop_all(bind=bind)
|
||||
for name in reversed(list(ENUMS)):
|
||||
op.execute(f"DROP TYPE IF EXISTS {name}")
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Counsel Scorecard backend application package."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Typed application settings, sourced from environment variables / .env."""
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
# Core
|
||||
app_env: str = "development"
|
||||
secret_key: str = "dev-insecure-change-me"
|
||||
|
||||
# Database (runtime = least-privilege "app" role)
|
||||
database_url: str = "postgresql+psycopg://app:app@localhost:5432/scoring"
|
||||
migration_database_url: str = "postgresql+psycopg://migrator:migrator@localhost:5432/scoring"
|
||||
|
||||
# Auth / sessions
|
||||
session_ttl_hours: int = 12
|
||||
login_max_attempts: int = 5
|
||||
login_lockout_minutes: int = 15
|
||||
|
||||
# Domain
|
||||
base_currency: str = "EUR"
|
||||
|
||||
# Bootstrap admin (seed)
|
||||
bootstrap_admin_email: str = "admin@example.com"
|
||||
bootstrap_admin_password: str = "admin12345"
|
||||
|
||||
# OpenTelemetry
|
||||
otel_enabled: bool = False
|
||||
otel_service_name: str = "counsel-scorecard-backend"
|
||||
otel_exporter_otlp_endpoint: str = "http://otel-collector:4317"
|
||||
otel_exporter_otlp_protocol: str = "grpc"
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
return self.app_env.lower() == "production"
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,36 @@
|
||||
"""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,
|
||||
)
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,54 @@
|
||||
"""FastAPI dependencies: DB session, current user, RBAC guards."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .db import get_db
|
||||
from .enums import UserRole
|
||||
from .errors import AuthenticationError, AuthorizationError
|
||||
from .models import AppUser
|
||||
from .services import auth as auth_service
|
||||
|
||||
SESSION_COOKIE = "session"
|
||||
|
||||
|
||||
def _extract_token(request: Request) -> str | None:
|
||||
token = request.cookies.get(SESSION_COOKIE)
|
||||
if token:
|
||||
return token
|
||||
header = request.headers.get("authorization")
|
||||
if header and header.lower().startswith("bearer "):
|
||||
return header[7:].strip()
|
||||
return None
|
||||
|
||||
|
||||
def get_current_user(request: Request, db: Session = Depends(get_db)) -> AppUser:
|
||||
token = _extract_token(request)
|
||||
if not token:
|
||||
raise AuthenticationError("Missing session token.")
|
||||
user = auth_service.resolve_session(db, token)
|
||||
if user is None:
|
||||
raise AuthenticationError("Invalid or expired session.")
|
||||
return user
|
||||
|
||||
|
||||
def require_role(*roles: UserRole):
|
||||
"""Dependency factory enforcing that the current user holds one of `roles`."""
|
||||
allowed: set[UserRole] = set(roles)
|
||||
|
||||
def _guard(user: AppUser = Depends(get_current_user)) -> AppUser:
|
||||
if user.role not in allowed:
|
||||
raise AuthorizationError(
|
||||
f"Role '{user.role}' is not permitted (requires one of: "
|
||||
f"{', '.join(sorted(r.value for r in allowed))})."
|
||||
)
|
||||
return user
|
||||
|
||||
return _guard
|
||||
|
||||
|
||||
def require_any(roles: Iterable[UserRole]):
|
||||
return require_role(*roles)
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Native PostgreSQL enums, mirrored as Python StrEnums.
|
||||
|
||||
The `.value` strings are the canonical DB enum labels (spec §H.3). Member names
|
||||
that would be invalid identifiers (e.g. starting with a digit) are prefixed.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class UserRole(StrEnum):
|
||||
admin = "admin"
|
||||
legal_ops = "legal_ops"
|
||||
matter_owner = "matter_owner"
|
||||
viewer = "viewer"
|
||||
|
||||
|
||||
class FirmStatus(StrEnum):
|
||||
active = "active"
|
||||
inactive = "inactive"
|
||||
blacklisted = "blacklisted"
|
||||
|
||||
|
||||
class MatterStatus(StrEnum):
|
||||
open = "open"
|
||||
in_progress = "in_progress"
|
||||
closed = "closed"
|
||||
cancelled = "cancelled"
|
||||
|
||||
|
||||
class MatterType(StrEnum):
|
||||
transactional = "transactional"
|
||||
advisory = "advisory"
|
||||
litigation = "litigation"
|
||||
regulatory = "regulatory"
|
||||
dispute = "dispute"
|
||||
|
||||
|
||||
class ComplexityBand(StrEnum):
|
||||
routine = "routine"
|
||||
standard = "standard"
|
||||
complex = "complex"
|
||||
bet_the_company = "bet_the_company"
|
||||
|
||||
|
||||
class ValueBand(StrEnum):
|
||||
lt_50k = "lt_50k"
|
||||
b50k_250k = "50k_250k"
|
||||
b250k_1m = "250k_1m"
|
||||
b1m_10m = "1m_10m"
|
||||
gt_10m = "gt_10m"
|
||||
|
||||
|
||||
class ConstrainedReason(StrEnum):
|
||||
regulator = "regulator"
|
||||
counterparty = "counterparty"
|
||||
sole_qualified = "sole_qualified"
|
||||
client_mandated = "client_mandated"
|
||||
other = "other"
|
||||
|
||||
|
||||
class ReviewCycleStatus(StrEnum):
|
||||
open = "open"
|
||||
closed = "closed"
|
||||
|
||||
|
||||
class FirmRankingStatus(StrEnum):
|
||||
provisional = "provisional"
|
||||
at_risk = "at_risk"
|
||||
watch = "watch"
|
||||
solid = "solid"
|
||||
top_performer = "top_performer"
|
||||
remove_candidate = "remove_candidate"
|
||||
|
||||
|
||||
# ─── Generic questionnaire engine ────────────────────────────────────────────
|
||||
class QuestionCategory(StrEnum):
|
||||
"""Drives scoring semantics: qualitative answers come from respondents,
|
||||
quantitative are computed from source data (invoices, etc.)."""
|
||||
qualitative = "qualitative"
|
||||
quantitative = "quantitative"
|
||||
|
||||
|
||||
class AnswerType(StrEnum):
|
||||
scale = "scale" # ordered options each mapping to a numeric value (e.g. 1-5)
|
||||
single_choice = "single_choice"
|
||||
multi_choice = "multi_choice"
|
||||
boolean = "boolean"
|
||||
numeric = "numeric"
|
||||
text = "text"
|
||||
|
||||
|
||||
class QuestionnaireStatus(StrEnum):
|
||||
draft = "draft"
|
||||
active = "active"
|
||||
archived = "archived"
|
||||
|
||||
|
||||
class ResponseStatus(StrEnum):
|
||||
draft = "draft"
|
||||
submitted = "submitted"
|
||||
locked = "locked"
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Domain errors + RFC 9457 (Problem Details) exception handlers."""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .config import get_settings
|
||||
|
||||
|
||||
class DomainError(Exception):
|
||||
status_code = status.HTTP_400_BAD_REQUEST
|
||||
error_type = "domain_error"
|
||||
title = "Domain error"
|
||||
|
||||
def __init__(self, detail: str, *, errors: list[dict] | None = None):
|
||||
super().__init__(detail)
|
||||
self.detail = detail
|
||||
self.errors = errors or []
|
||||
|
||||
|
||||
class AuthenticationError(DomainError):
|
||||
status_code = status.HTTP_401_UNAUTHORIZED
|
||||
error_type = "authentication_error"
|
||||
title = "Authentication required"
|
||||
|
||||
|
||||
class AuthorizationError(DomainError):
|
||||
status_code = status.HTTP_403_FORBIDDEN
|
||||
error_type = "authorization_error"
|
||||
title = "Forbidden"
|
||||
|
||||
|
||||
class NotFoundError(DomainError):
|
||||
status_code = status.HTTP_404_NOT_FOUND
|
||||
error_type = "not_found"
|
||||
title = "Resource not found"
|
||||
|
||||
|
||||
class ConflictError(DomainError):
|
||||
status_code = status.HTTP_409_CONFLICT
|
||||
error_type = "conflict"
|
||||
title = "Conflict"
|
||||
|
||||
|
||||
class ValidationError(DomainError):
|
||||
status_code = status.HTTP_422_UNPROCESSABLE_ENTITY
|
||||
error_type = "validation_error"
|
||||
title = "Invalid input"
|
||||
|
||||
|
||||
def _problem(request: Request, *, status_code: int, error_type: str, title: str,
|
||||
detail: str, errors: list[dict] | None = None) -> JSONResponse:
|
||||
body = {
|
||||
"type": error_type,
|
||||
"title": title,
|
||||
"status": status_code,
|
||||
"detail": detail,
|
||||
"instance": str(request.url.path),
|
||||
}
|
||||
if errors:
|
||||
body["errors"] = errors
|
||||
return JSONResponse(status_code=status_code, content=body,
|
||||
media_type="application/problem+json")
|
||||
|
||||
|
||||
def install_error_handlers(app: FastAPI) -> None:
|
||||
settings = get_settings()
|
||||
|
||||
@app.exception_handler(DomainError)
|
||||
async def _domain(request: Request, exc: DomainError):
|
||||
return _problem(
|
||||
request,
|
||||
status_code=exc.status_code,
|
||||
error_type=exc.error_type,
|
||||
title=exc.title,
|
||||
detail=exc.detail,
|
||||
errors=exc.errors,
|
||||
)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def _validation(request: Request, exc: RequestValidationError):
|
||||
errors = [
|
||||
{"field": ".".join(str(p) for p in e["loc"][1:]), "code": e["type"]}
|
||||
for e in exc.errors()
|
||||
]
|
||||
return _problem(
|
||||
request,
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
error_type="validation_error",
|
||||
title="Invalid input",
|
||||
detail="One or more fields failed validation.",
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def _unhandled(request: Request, exc: Exception):
|
||||
detail = "Internal server error." if settings.is_production else f"{type(exc).__name__}: {exc}"
|
||||
return _problem(
|
||||
request,
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
error_type="internal_error",
|
||||
title="Internal server error",
|
||||
detail=detail,
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Structured JSON logging to stdout (Docker captures it; OTel can ingest via filelog)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
payload = {
|
||||
"ts": dt.datetime.fromtimestamp(record.created, dt.timezone.utc).isoformat(),
|
||||
"level": record.levelname,
|
||||
"logger": record.name,
|
||||
"message": record.getMessage(),
|
||||
}
|
||||
if record.exc_info:
|
||||
payload["exc"] = self.formatException(record.exc_info)
|
||||
for key in ("request_id", "trace_id", "span_id"):
|
||||
if hasattr(record, key):
|
||||
payload[key] = getattr(record, key)
|
||||
return json.dumps(payload, ensure_ascii=False)
|
||||
|
||||
|
||||
def configure_logging(level: int = logging.INFO) -> None:
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(JsonFormatter())
|
||||
root = logging.getLogger()
|
||||
root.handlers.clear()
|
||||
root.addHandler(handler)
|
||||
root.setLevel(level)
|
||||
# Quiet noisy access logs; uvicorn still logs errors.
|
||||
logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""FastAPI application entrypoint."""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from . import __version__
|
||||
from .config import get_settings
|
||||
from .db import engine
|
||||
from .errors import install_error_handlers
|
||||
from .logging_config import configure_logging
|
||||
from .observability import setup_observability
|
||||
from .routers import (
|
||||
auth,
|
||||
firms,
|
||||
health,
|
||||
matters,
|
||||
questionnaires,
|
||||
questions,
|
||||
responses,
|
||||
review_cycles,
|
||||
search,
|
||||
users,
|
||||
)
|
||||
|
||||
API_PREFIX = "/api/v1"
|
||||
|
||||
settings = get_settings()
|
||||
configure_logging()
|
||||
|
||||
app = FastAPI(
|
||||
title="Counsel Scorecard API",
|
||||
version=__version__,
|
||||
description="Backend for the external-counsel scoring platform.",
|
||||
docs_url=f"{API_PREFIX}/docs",
|
||||
redoc_url=None,
|
||||
openapi_url=f"{API_PREFIX}/openapi.json",
|
||||
)
|
||||
|
||||
install_error_handlers(app)
|
||||
setup_observability(app, engine)
|
||||
|
||||
for router in (
|
||||
health.router,
|
||||
auth.router,
|
||||
users.router,
|
||||
firms.router,
|
||||
matters.router,
|
||||
questions.router,
|
||||
questionnaires.router,
|
||||
responses.router,
|
||||
review_cycles.router,
|
||||
search.router,
|
||||
):
|
||||
app.include_router(router, prefix=API_PREFIX)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Import all models so Base.metadata is fully populated (Alembic, create_all)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import Base
|
||||
from .firm import Firm, FirmJurisdiction, FirmPracticeArea, Office
|
||||
from .identity import AppSetting, AppUser, AuditLog, Session
|
||||
from .matter import Matter
|
||||
from .questionnaire import (
|
||||
AnswerOption,
|
||||
Question,
|
||||
Questionnaire,
|
||||
QuestionnaireQuestion,
|
||||
Response,
|
||||
ResponseItem,
|
||||
ResponseRevision,
|
||||
)
|
||||
from .reference import Jurisdiction, PracticeArea
|
||||
from .review import ReviewCycle, ScoreSnapshot
|
||||
|
||||
__all__ = [
|
||||
"Base",
|
||||
"AppUser",
|
||||
"Session",
|
||||
"AppSetting",
|
||||
"AuditLog",
|
||||
"PracticeArea",
|
||||
"Jurisdiction",
|
||||
"Firm",
|
||||
"Office",
|
||||
"FirmPracticeArea",
|
||||
"FirmJurisdiction",
|
||||
"Matter",
|
||||
"ReviewCycle",
|
||||
"ScoreSnapshot",
|
||||
"Question",
|
||||
"AnswerOption",
|
||||
"Questionnaire",
|
||||
"QuestionnaireQuestion",
|
||||
"Response",
|
||||
"ResponseItem",
|
||||
"ResponseRevision",
|
||||
]
|
||||
@@ -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()
|
||||
)
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Firms (law firms), their offices, and N:N links to dictionaries."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import Boolean, Computed, ForeignKey, Index, Text, text
|
||||
from sqlalchemy.dialects.postgresql import TSVECTOR
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from ..enums import FirmStatus
|
||||
from .base import Base, TimestampMixin, UUIDPkMixin
|
||||
from .types import pg_enum
|
||||
|
||||
# Language-agnostic 'simple' config (no stemming) — safe default for mixed PL/EN
|
||||
# content. Swap to 'english'/'polish' per deployment if dictionaries are installed.
|
||||
_FIRM_TSV = "to_tsvector('simple', coalesce(name,'') || ' ' || coalesce(legal_name,'') || ' ' || coalesce(notes,''))"
|
||||
|
||||
|
||||
class Firm(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "firm"
|
||||
|
||||
name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
legal_name: Mapped[str | None] = mapped_column(Text)
|
||||
status: Mapped[FirmStatus] = mapped_column(
|
||||
pg_enum(FirmStatus, "firm_status"), nullable=False, server_default=FirmStatus.active.value
|
||||
)
|
||||
website: Mapped[str | None] = mapped_column(Text)
|
||||
notes: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
search_vector: Mapped[str | None] = mapped_column(
|
||||
TSVECTOR, Computed(_FIRM_TSV, persisted=True)
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("uq_firm_name_lower", text("lower(name)"), unique=True),
|
||||
Index("ix_firm_status", "status"),
|
||||
Index("ix_firm_search", "search_vector", postgresql_using="gin"),
|
||||
)
|
||||
|
||||
|
||||
class Office(UUIDPkMixin, Base):
|
||||
__tablename__ = "office"
|
||||
|
||||
firm_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("firm.id", ondelete="RESTRICT"), nullable=False
|
||||
)
|
||||
jurisdiction_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("jurisdiction.id"), nullable=False
|
||||
)
|
||||
city: Mapped[str | None] = mapped_column(Text)
|
||||
is_headquarters: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, server_default=text("false")
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_office_firm_id", "firm_id"),
|
||||
Index("ix_office_jurisdiction_id", "jurisdiction_id"),
|
||||
Index(
|
||||
"uq_office_firm_hq", "firm_id", unique=True,
|
||||
postgresql_where=text("is_headquarters"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class FirmPracticeArea(Base):
|
||||
__tablename__ = "firm_practice_area"
|
||||
|
||||
firm_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("firm.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
practice_area_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("practice_area.id", ondelete="RESTRICT"), primary_key=True
|
||||
)
|
||||
|
||||
__table_args__ = (Index("ix_firm_practice_area_practice_area_id", "practice_area_id"),)
|
||||
|
||||
|
||||
class FirmJurisdiction(Base):
|
||||
__tablename__ = "firm_jurisdiction"
|
||||
|
||||
firm_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("firm.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
jurisdiction_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("jurisdiction.id", ondelete="RESTRICT"), primary_key=True
|
||||
)
|
||||
|
||||
__table_args__ = (Index("ix_firm_jurisdiction_jurisdiction_id", "jurisdiction_id"),)
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Identity, sessions, instance settings, audit log."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, String, Text, Uuid, text
|
||||
from sqlalchemy.dialects.postgresql import INET, JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from ..enums import UserRole
|
||||
from .base import Base, TimestampMixin, UUIDPkMixin
|
||||
from .types import pg_enum
|
||||
|
||||
|
||||
class AppUser(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "app_user"
|
||||
|
||||
email: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(Text, nullable=False) # Argon2id
|
||||
role: Mapped[UserRole] = mapped_column(
|
||||
pg_enum(UserRole, "user_role"), nullable=False, server_default=UserRole.matter_owner.value
|
||||
)
|
||||
full_name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||
|
||||
__table_args__ = (
|
||||
Index("uq_app_user_email_lower", text("lower(email)"), unique=True),
|
||||
)
|
||||
|
||||
|
||||
class Session(UUIDPkMixin, Base):
|
||||
__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(INET)
|
||||
created_at: Mapped[dt.datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=text("now()")
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_session_user_id", "user_id"),
|
||||
Index("ix_session_expires_at", "expires_at"),
|
||||
)
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
"""Instance config as auditable key/value (e.g. base_currency)."""
|
||||
__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] = mapped_column(Uuid(as_uuid=True), nullable=False)
|
||||
ip: Mapped[str | None] = mapped_column(INET)
|
||||
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"),
|
||||
)
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Matters — the unit of work a firm is engaged for and later evaluated on."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
CHAR,
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
Computed,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Numeric,
|
||||
Text,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import TSVECTOR
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from ..enums import (
|
||||
ComplexityBand,
|
||||
ConstrainedReason,
|
||||
MatterStatus,
|
||||
MatterType,
|
||||
ValueBand,
|
||||
)
|
||||
from .base import Base, TimestampMixin, UUIDPkMixin
|
||||
from .types import pg_enum
|
||||
|
||||
_MATTER_TSV = "to_tsvector('simple', coalesce(reference,'') || ' ' || coalesce(title,''))"
|
||||
|
||||
|
||||
class Matter(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "matter"
|
||||
|
||||
reference: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
|
||||
title: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
|
||||
firm_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("firm.id"), nullable=False)
|
||||
practice_area_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("practice_area.id"), nullable=False
|
||||
)
|
||||
jurisdiction_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("jurisdiction.id"), nullable=False
|
||||
)
|
||||
matter_owner_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("app_user.id"), nullable=False)
|
||||
parent_matter_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("matter.id"))
|
||||
|
||||
# Optional cost context (powers budget_adherence once invoices exist — MVP-1).
|
||||
budget_estimate: Mapped[float | None] = mapped_column(Numeric(14, 2))
|
||||
budget_currency: Mapped[str | None] = mapped_column(CHAR(3))
|
||||
|
||||
# Materiality axes (spec F.3.1).
|
||||
matter_type: Mapped[MatterType] = mapped_column(
|
||||
pg_enum(MatterType, "matter_type"),
|
||||
nullable=False,
|
||||
server_default=MatterType.advisory.value,
|
||||
)
|
||||
complexity_band: Mapped[ComplexityBand] = mapped_column(
|
||||
pg_enum(ComplexityBand, "complexity_band"),
|
||||
nullable=False,
|
||||
server_default=ComplexityBand.standard.value,
|
||||
)
|
||||
value_band: Mapped[ValueBand | None] = mapped_column(pg_enum(ValueBand, "value_band"))
|
||||
is_constrained_choice: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, server_default=text("false")
|
||||
)
|
||||
constrained_reason: Mapped[ConstrainedReason | None] = mapped_column(
|
||||
pg_enum(ConstrainedReason, "constrained_reason")
|
||||
)
|
||||
|
||||
status: Mapped[MatterStatus] = mapped_column(
|
||||
pg_enum(MatterStatus, "matter_status"),
|
||||
nullable=False,
|
||||
server_default=MatterStatus.open.value,
|
||||
)
|
||||
opened_at: Mapped[dt.datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=text("now()")
|
||||
)
|
||||
closed_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
search_vector: Mapped[str | None] = mapped_column(
|
||||
TSVECTOR, Computed(_MATTER_TSV, persisted=True)
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint("closed_at IS NULL OR closed_at >= opened_at", name="closed_after_opened"),
|
||||
Index("ix_matter_firm_id", "firm_id"),
|
||||
Index("ix_matter_practice_area_id", "practice_area_id"),
|
||||
Index("ix_matter_jurisdiction_id", "jurisdiction_id"),
|
||||
Index("ix_matter_matter_owner_id", "matter_owner_id"),
|
||||
Index("ix_matter_status", "status"),
|
||||
Index("ix_matter_search", "search_vector", postgresql_using="gin"),
|
||||
)
|
||||
@@ -0,0 +1,248 @@
|
||||
"""Generic questionnaire engine.
|
||||
|
||||
Generalizes the spec's evaluation model so questions/answers/sets are data, not code:
|
||||
|
||||
question → a criterion / survey question (generalizes `criterion`)
|
||||
answer_option → the predefined possible answers (e.g. the 1-5 anchors)
|
||||
questionnaire → a grouped, versioned set of questions (the evaluation form)
|
||||
questionnaire_question→ M:N link carrying display order, weight, required flag
|
||||
response → one filled-in questionnaire (generalizes `evaluation`)
|
||||
response_item → one answer within a response (generalizes `evaluation_score`)
|
||||
response_revision → append-only history snapshot of a response (results-with-history)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
Computed,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
Numeric,
|
||||
SmallInteger,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
Uuid,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB, TSVECTOR
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from ..enums import (
|
||||
AnswerType,
|
||||
QuestionCategory,
|
||||
QuestionnaireStatus,
|
||||
ResponseStatus,
|
||||
)
|
||||
from .base import Base, TimestampMixin, UUIDPkMixin
|
||||
from .types import pg_enum
|
||||
|
||||
_QUESTION_TSV = (
|
||||
"to_tsvector('simple', coalesce(key,'') || ' ' || coalesce(label,'') "
|
||||
"|| ' ' || coalesce(help_text,''))"
|
||||
)
|
||||
|
||||
|
||||
class Question(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "question"
|
||||
|
||||
key: Mapped[str] = mapped_column(Text, nullable=False, unique=True) # e.g. quality_of_advice
|
||||
label: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
help_text: Mapped[str | None] = mapped_column(Text)
|
||||
category: Mapped[QuestionCategory] = mapped_column(
|
||||
pg_enum(QuestionCategory, "question_category"),
|
||||
nullable=False,
|
||||
server_default=QuestionCategory.qualitative.value,
|
||||
)
|
||||
answer_type: Mapped[AnswerType] = mapped_column(
|
||||
pg_enum(AnswerType, "answer_type"),
|
||||
nullable=False,
|
||||
server_default=AnswerType.scale.value,
|
||||
)
|
||||
scale_min: Mapped[int] = mapped_column(SmallInteger, nullable=False, server_default=text("1"))
|
||||
scale_max: Mapped[int] = mapped_column(SmallInteger, nullable=False, server_default=text("5"))
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||
|
||||
search_vector: Mapped[str | None] = mapped_column(
|
||||
TSVECTOR, Computed(_QUESTION_TSV, persisted=True)
|
||||
)
|
||||
|
||||
options: Mapped[list["AnswerOption"]] = relationship(
|
||||
back_populates="question", cascade="all, delete-orphan", order_by="AnswerOption.display_order"
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint("scale_max >= scale_min", name="scale_order"),
|
||||
Index("ix_question_search", "search_vector", postgresql_using="gin"),
|
||||
)
|
||||
|
||||
|
||||
class AnswerOption(UUIDPkMixin, Base):
|
||||
"""A possible answer for a question; `value` is its numeric contribution to scoring."""
|
||||
__tablename__ = "answer_option"
|
||||
|
||||
question_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("question.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
code: Mapped[str] = mapped_column(Text, nullable=False) # e.g. "5"
|
||||
label: Mapped[str] = mapped_column(Text, nullable=False) # e.g. anchor description
|
||||
value: Mapped[float | None] = mapped_column(Numeric(6, 2)) # numeric score, null for free text
|
||||
display_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||
|
||||
question: Mapped["Question"] = relationship(back_populates="options")
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("question_id", "code", name="uq_answer_option_question_code"),
|
||||
Index("ix_answer_option_question_id", "question_id"),
|
||||
)
|
||||
|
||||
|
||||
class Questionnaire(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "questionnaire"
|
||||
|
||||
key: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
title: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
description: Mapped[str | None] = mapped_column(Text)
|
||||
status: Mapped[QuestionnaireStatus] = mapped_column(
|
||||
pg_enum(QuestionnaireStatus, "questionnaire_status"),
|
||||
nullable=False,
|
||||
server_default=QuestionnaireStatus.draft.value,
|
||||
)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("1"))
|
||||
# Optional binding to a review cycle (the spec versions weights per cycle).
|
||||
review_cycle_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("review_cycle.id"))
|
||||
|
||||
items: Mapped[list["QuestionnaireQuestion"]] = relationship(
|
||||
back_populates="questionnaire",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="QuestionnaireQuestion.display_order",
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("key", "version", name="uq_questionnaire_key_version"),
|
||||
)
|
||||
|
||||
|
||||
class QuestionnaireQuestion(Base):
|
||||
"""Links a question into a questionnaire with order, weight, and required flag."""
|
||||
__tablename__ = "questionnaire_question"
|
||||
|
||||
questionnaire_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("questionnaire.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
question_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("question.id", ondelete="RESTRICT"), primary_key=True
|
||||
)
|
||||
display_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
|
||||
weight: Mapped[float] = mapped_column(Numeric(5, 4), nullable=False, server_default=text("0"))
|
||||
is_required: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||
|
||||
questionnaire: Mapped["Questionnaire"] = relationship(back_populates="items")
|
||||
question: Mapped["Question"] = relationship()
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint("weight >= 0", name="weight_non_negative"),
|
||||
Index("ix_questionnaire_question_question_id", "question_id"),
|
||||
)
|
||||
|
||||
|
||||
class Response(UUIDPkMixin, TimestampMixin, Base):
|
||||
"""One filled-in questionnaire (an evaluation)."""
|
||||
__tablename__ = "response"
|
||||
|
||||
questionnaire_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("questionnaire.id"), nullable=False
|
||||
)
|
||||
# Reviewer identity is pseudonymized (spec §H.2 GDPR): respondent_id may be nulled
|
||||
# on account deletion while respondent_ref keeps uniqueness/audit intact.
|
||||
respondent_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
|
||||
respondent_ref: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), nullable=False)
|
||||
|
||||
# Domain context (all optional so the engine is reusable beyond Counsel Scorecard).
|
||||
matter_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("matter.id"))
|
||||
firm_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("firm.id"))
|
||||
review_cycle_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("review_cycle.id"))
|
||||
|
||||
status: Mapped[ResponseStatus] = mapped_column(
|
||||
pg_enum(ResponseStatus, "response_status"),
|
||||
nullable=False,
|
||||
server_default=ResponseStatus.draft.value,
|
||||
)
|
||||
recommend: Mapped[bool | None] = mapped_column(Boolean) # "would recommend" toggle
|
||||
is_constrained: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, server_default=text("false")
|
||||
)
|
||||
overall_comment: Mapped[str | None] = mapped_column(Text) # ≤280 chars (validated in Pydantic)
|
||||
score: Mapped[float | None] = mapped_column(Numeric(5, 2)) # computed weighted result (0-100)
|
||||
revision: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("1"))
|
||||
opened_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
submitted_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
search_vector: Mapped[str | None] = mapped_column(
|
||||
TSVECTOR,
|
||||
Computed("to_tsvector('simple', coalesce(overall_comment,''))", persisted=True),
|
||||
)
|
||||
|
||||
items: Mapped[list["ResponseItem"]] = relationship(
|
||||
back_populates="response", cascade="all, delete-orphan"
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"questionnaire_id", "matter_id", "respondent_ref",
|
||||
name="uq_response_questionnaire_matter_respondent",
|
||||
),
|
||||
Index("ix_response_firm_cycle", "firm_id", "review_cycle_id"),
|
||||
Index("ix_response_matter_id", "matter_id"),
|
||||
Index("ix_response_respondent_id", "respondent_id"),
|
||||
Index("ix_response_status", "status"),
|
||||
Index("ix_response_search", "search_vector", postgresql_using="gin"),
|
||||
)
|
||||
|
||||
|
||||
class ResponseItem(UUIDPkMixin, Base):
|
||||
"""One answer within a response."""
|
||||
__tablename__ = "response_item"
|
||||
|
||||
response_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("response.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
question_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("question.id"), nullable=False)
|
||||
answer_option_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("answer_option.id"))
|
||||
numeric_value: Mapped[float | None] = mapped_column(Numeric(6, 2))
|
||||
bool_value: Mapped[bool | None] = mapped_column(Boolean)
|
||||
text_value: Mapped[str | None] = mapped_column(Text)
|
||||
comment: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("response_id", "question_id", name="uq_response_item_response_question"),
|
||||
Index("ix_response_item_response_id", "response_id"),
|
||||
Index("ix_response_item_question_id", "question_id"),
|
||||
)
|
||||
|
||||
|
||||
class ResponseRevision(UUIDPkMixin, Base):
|
||||
"""Append-only history: a full JSON snapshot of a response at each save/submit."""
|
||||
__tablename__ = "response_revision"
|
||||
|
||||
response_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("response.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
snapshot: Mapped[dict] = mapped_column(JSONB, nullable=False)
|
||||
changed_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
|
||||
change_reason: 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("response_id", "revision_no", name="uq_response_revision_no"),
|
||||
Index("ix_response_revision_response_id", "response_id"),
|
||||
)
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Editable dictionaries: practice areas and jurisdictions."""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Boolean, CHAR, Text, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base, UUIDPkMixin
|
||||
|
||||
|
||||
class PracticeArea(UUIDPkMixin, Base):
|
||||
__tablename__ = "practice_area"
|
||||
|
||||
code: Mapped[str] = mapped_column(Text, nullable=False, unique=True) # e.g. m_and_a
|
||||
label: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||
|
||||
|
||||
class Jurisdiction(UUIDPkMixin, Base):
|
||||
__tablename__ = "jurisdiction"
|
||||
|
||||
code: Mapped[str] = mapped_column(CHAR(2), nullable=False, unique=True) # ISO 3166-1 alpha-2
|
||||
label: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Review cycles and the immutable per-firm score snapshots they produce."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
Date,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
Numeric,
|
||||
SmallInteger,
|
||||
Text,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from ..enums import FirmRankingStatus, ReviewCycleStatus
|
||||
from .base import Base, UUIDPkMixin
|
||||
from .types import pg_enum
|
||||
|
||||
|
||||
class ReviewCycle(UUIDPkMixin, Base):
|
||||
__tablename__ = "review_cycle"
|
||||
|
||||
name: Mapped[str] = mapped_column(Text, nullable=False) # e.g. "Q2 2026"
|
||||
start_date: Mapped[dt.date] = mapped_column(Date, nullable=False)
|
||||
end_date: Mapped[dt.date] = mapped_column(Date, nullable=False)
|
||||
status: Mapped[ReviewCycleStatus] = mapped_column(
|
||||
pg_enum(ReviewCycleStatus, "review_cycle_status"),
|
||||
nullable=False,
|
||||
server_default=ReviewCycleStatus.open.value,
|
||||
)
|
||||
config_version: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("1"))
|
||||
min_evaluations: Mapped[int] = mapped_column(
|
||||
SmallInteger, nullable=False, server_default=text("3")
|
||||
)
|
||||
closed_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
closed_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint("end_date >= start_date", name="end_after_start"),
|
||||
)
|
||||
|
||||
|
||||
class ScoreSnapshot(UUIDPkMixin, Base):
|
||||
"""Immutable materialization per (firm, cycle), computed at cycle close (spec H.4)."""
|
||||
__tablename__ = "score_snapshot"
|
||||
|
||||
firm_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("firm.id"), nullable=False)
|
||||
review_cycle_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("review_cycle.id"), nullable=False
|
||||
)
|
||||
composite_score: Mapped[float] = mapped_column(Numeric(5, 2), nullable=False)
|
||||
qualitative_score: Mapped[float | None] = mapped_column(Numeric(5, 2))
|
||||
quantitative_score: Mapped[float | None] = mapped_column(Numeric(5, 2))
|
||||
data_completeness: Mapped[float | None] = mapped_column(Numeric(5, 4))
|
||||
evaluation_count: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
|
||||
invoice_count: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
|
||||
delta: Mapped[float | None] = mapped_column(Numeric(6, 2))
|
||||
ranking_status: Mapped[FirmRankingStatus] = mapped_column(
|
||||
pg_enum(FirmRankingStatus, "firm_ranking_status"),
|
||||
nullable=False,
|
||||
server_default=FirmRankingStatus.provisional.value,
|
||||
)
|
||||
config_version: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("1"))
|
||||
breakdown: Mapped[dict | None] = mapped_column(JSONB)
|
||||
computed_at: Mapped[dt.datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=text("now()")
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("uq_score_snapshot_firm_cycle", "firm_id", "review_cycle_id", unique=True),
|
||||
Index("ix_score_snapshot_review_cycle_id", "review_cycle_id"),
|
||||
Index("ix_score_snapshot_firm_id", "firm_id"),
|
||||
Index("ix_score_snapshot_ranking_status", "ranking_status"),
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Helpers for mapping Python StrEnums onto pre-created native PG enum types.
|
||||
|
||||
`create_type=False` because the Alembic migration owns enum creation (the runtime
|
||||
`app` role has no DDL). `values_callable` makes the DB labels the enum *values*
|
||||
(not member names) — required where they differ, e.g. ValueBand.b50k_250k → "50k_250k".
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy.dialects.postgresql import ENUM as PGEnum
|
||||
|
||||
|
||||
def pg_enum(py_enum, name: str) -> PGEnum:
|
||||
# postgresql.ENUM (not the generic sa.Enum) reliably honors create_type=False,
|
||||
# so create_all() never emits CREATE TYPE — the 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],
|
||||
)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""OpenTelemetry wiring — traces, metrics and logs exported via OTLP/gRPC to the
|
||||
OTel Collector, which forwards to ClickHouse for HyperDX (spec set "S3").
|
||||
|
||||
Safe no-op when OTEL_ENABLED is false, so the backend runs standalone without a
|
||||
collector. Instrumentation is best-effort: any import/setup failure is logged and
|
||||
swallowed rather than blocking startup.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def setup_observability(app, engine) -> None:
|
||||
from .config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.otel_enabled:
|
||||
logger.info("OpenTelemetry disabled (OTEL_ENABLED=false).")
|
||||
return
|
||||
|
||||
try:
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
|
||||
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.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
|
||||
endpoint = settings.otel_exporter_otlp_endpoint
|
||||
resource = Resource.create(
|
||||
{
|
||||
"service.name": settings.otel_service_name,
|
||||
"service.version": __import__("app").__version__,
|
||||
"deployment.environment": settings.app_env,
|
||||
}
|
||||
)
|
||||
|
||||
# Traces
|
||||
tracer_provider = TracerProvider(resource=resource)
|
||||
tracer_provider.add_span_processor(
|
||||
BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint, insecure=True))
|
||||
)
|
||||
trace.set_tracer_provider(tracer_provider)
|
||||
|
||||
# Metrics
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=endpoint, insecure=True)
|
||||
)
|
||||
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))
|
||||
|
||||
# Auto-instrumentation
|
||||
FastAPIInstrumentor.instrument_app(app, tracer_provider=tracer_provider)
|
||||
SQLAlchemyInstrumentor().instrument(engine=engine, tracer_provider=tracer_provider)
|
||||
|
||||
logger.info("OpenTelemetry enabled → exporting OTLP to %s", endpoint)
|
||||
except Exception: # noqa: BLE001 — never let telemetry break the app
|
||||
logger.exception("OpenTelemetry setup failed; continuing without instrumentation.")
|
||||
@@ -0,0 +1 @@
|
||||
"""HTTP routers. Thin: validate, call services, map results. No domain logic, no SQL."""
|
||||
@@ -0,0 +1,65 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
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, get_current_user
|
||||
from ..errors import AuthenticationError
|
||||
from ..models import AppUser
|
||||
from ..schemas import LoginRequest, LoginResponse, MessageResponse, UserOut
|
||||
from ..services import audit
|
||||
from ..services import auth as auth_service
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
@router.post("/login", response_model=LoginResponse)
|
||||
def login(payload: LoginRequest, request: Request, response: Response,
|
||||
db: Session = Depends(get_db)) -> LoginResponse:
|
||||
ip = request.client.host if request.client else None
|
||||
user = auth_service.authenticate(db, payload.email, payload.password)
|
||||
if user is None:
|
||||
audit.record(db, action="auth.login.denied", entity_type="app_user",
|
||||
entity_id=uuid.UUID(int=0), result="denied", ip=ip)
|
||||
db.commit()
|
||||
raise AuthenticationError("Invalid email or password.")
|
||||
|
||||
session, token = auth_service.create_session(db, user, ip=ip)
|
||||
audit.record(db, action="auth.login", entity_type="session", entity_id=session.id,
|
||||
actor_id=user.id, ip=ip)
|
||||
db.commit()
|
||||
|
||||
response.set_cookie(
|
||||
key=SESSION_COOKIE,
|
||||
value=token,
|
||||
max_age=settings.session_ttl_hours * 3600,
|
||||
httponly=True,
|
||||
secure=settings.is_production,
|
||||
samesite="strict",
|
||||
path="/api",
|
||||
)
|
||||
return LoginResponse(token=token, user=UserOut.model_validate(user))
|
||||
|
||||
|
||||
@router.post("/logout", response_model=MessageResponse)
|
||||
def logout(request: Request, response: Response, db: Session = Depends(get_db)) -> MessageResponse:
|
||||
token = request.cookies.get(SESSION_COOKIE)
|
||||
if not token:
|
||||
header = request.headers.get("authorization", "")
|
||||
if header.lower().startswith("bearer "):
|
||||
token = header[7:].strip()
|
||||
if token:
|
||||
auth_service.revoke_session(db, token)
|
||||
db.commit()
|
||||
response.delete_cookie(SESSION_COOKIE, path="/api")
|
||||
return MessageResponse(message="Logged out.")
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
def me(user: AppUser = Depends(get_current_user)) -> AppUser:
|
||||
return user
|
||||
@@ -0,0 +1,60 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import get_current_user, require_role
|
||||
from ..enums import UserRole
|
||||
from ..errors import NotFoundError
|
||||
from ..models import AppUser, Firm
|
||||
from ..schemas import FirmCreate, FirmOut, FirmUpdate
|
||||
from ..services import audit
|
||||
|
||||
router = APIRouter(prefix="/firms", tags=["firms"])
|
||||
|
||||
_WRITE = require_role(UserRole.admin, UserRole.legal_ops)
|
||||
|
||||
|
||||
@router.post("", response_model=FirmOut, status_code=201)
|
||||
def create_firm(payload: FirmCreate, db: Session = Depends(get_db),
|
||||
actor: AppUser = Depends(_WRITE)) -> Firm:
|
||||
firm = Firm(**payload.model_dump())
|
||||
db.add(firm)
|
||||
db.flush()
|
||||
audit.record(db, action="firm.created", entity_type="firm", entity_id=firm.id,
|
||||
actor_id=actor.id)
|
||||
db.commit()
|
||||
return firm
|
||||
|
||||
|
||||
@router.get("", response_model=list[FirmOut])
|
||||
def list_firms(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[Firm]:
|
||||
return list(db.scalars(select(Firm).order_by(Firm.name)))
|
||||
|
||||
|
||||
@router.get("/{firm_id}", response_model=FirmOut)
|
||||
def get_firm(firm_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> Firm:
|
||||
firm = db.get(Firm, firm_id)
|
||||
if firm is None:
|
||||
raise NotFoundError("Firm not found.")
|
||||
return firm
|
||||
|
||||
|
||||
@router.patch("/{firm_id}", response_model=FirmOut)
|
||||
def update_firm(firm_id: uuid.UUID, payload: FirmUpdate, db: Session = Depends(get_db),
|
||||
actor: AppUser = Depends(_WRITE)) -> Firm:
|
||||
firm = db.get(Firm, firm_id)
|
||||
if firm is None:
|
||||
raise NotFoundError("Firm not found.")
|
||||
for field, value in payload.model_dump(exclude_unset=True).items():
|
||||
setattr(firm, field, value)
|
||||
audit.record(db, action="firm.updated", entity_type="firm", entity_id=firm.id,
|
||||
actor_id=actor.id)
|
||||
db.commit()
|
||||
return firm
|
||||
@@ -0,0 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health(db: Session = Depends(get_db)) -> dict:
|
||||
"""Internal liveness/readiness — checks the DB connection. Minimal payload (no version)."""
|
||||
db.execute(text("SELECT 1"))
|
||||
return {"status": "ok"}
|
||||
@@ -0,0 +1,55 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import get_current_user, require_role
|
||||
from ..enums import UserRole
|
||||
from ..errors import NotFoundError
|
||||
from ..models import AppUser, Matter
|
||||
from ..schemas import MatterCreate, MatterOut
|
||||
from ..services import audit
|
||||
|
||||
router = APIRouter(prefix="/matters", tags=["matters"])
|
||||
|
||||
_WRITE = require_role(UserRole.admin, UserRole.legal_ops, UserRole.matter_owner)
|
||||
|
||||
|
||||
@router.post("", response_model=MatterOut, status_code=201)
|
||||
def create_matter(payload: MatterCreate, db: Session = Depends(get_db),
|
||||
actor: AppUser = Depends(_WRITE)) -> Matter:
|
||||
data = payload.model_dump()
|
||||
if data.get("matter_owner_id") is None:
|
||||
data["matter_owner_id"] = actor.id
|
||||
matter = Matter(**data)
|
||||
db.add(matter)
|
||||
db.flush()
|
||||
audit.record(db, action="matter.created", entity_type="matter", entity_id=matter.id,
|
||||
actor_id=actor.id)
|
||||
db.commit()
|
||||
return matter
|
||||
|
||||
|
||||
@router.get("", response_model=list[MatterOut])
|
||||
def list_matters(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> list[Matter]:
|
||||
stmt = select(Matter).order_by(Matter.created_at.desc())
|
||||
# Matter owners see only their own matters (spec RBAC).
|
||||
if user.role == UserRole.matter_owner:
|
||||
stmt = stmt.where(Matter.matter_owner_id == user.id)
|
||||
return list(db.scalars(stmt))
|
||||
|
||||
|
||||
@router.get("/{matter_id}", response_model=MatterOut)
|
||||
def get_matter(matter_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Matter:
|
||||
matter = db.get(Matter, matter_id)
|
||||
if matter is None:
|
||||
raise NotFoundError("Matter not found.")
|
||||
if user.role == UserRole.matter_owner and matter.matter_owner_id != user.id:
|
||||
raise NotFoundError("Matter not found.")
|
||||
return matter
|
||||
@@ -0,0 +1,72 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import get_current_user, require_role
|
||||
from ..enums import UserRole
|
||||
from ..errors import NotFoundError, ValidationError
|
||||
from ..models import AppUser, Question, Questionnaire, QuestionnaireQuestion
|
||||
from ..schemas import QuestionnaireCreate, QuestionnaireOut
|
||||
from ..services import audit
|
||||
|
||||
router = APIRouter(prefix="/questionnaires", tags=["questionnaire"])
|
||||
|
||||
_WRITE = require_role(UserRole.admin, UserRole.legal_ops)
|
||||
|
||||
|
||||
@router.post("", response_model=QuestionnaireOut, status_code=201)
|
||||
def create_questionnaire(payload: QuestionnaireCreate, db: Session = Depends(get_db),
|
||||
actor: AppUser = Depends(_WRITE)) -> Questionnaire:
|
||||
# Validate referenced questions exist.
|
||||
for item in payload.items:
|
||||
if db.get(Question, item.question_id) is None:
|
||||
raise ValidationError(f"Question {item.question_id} does not exist.")
|
||||
|
||||
# Weights, if any are non-zero, should sum to ~1.0 (spec §F.2 / criterion_weight).
|
||||
total = sum((item.weight for item in payload.items), Decimal("0"))
|
||||
if total > 0 and abs(total - Decimal("1")) > Decimal("0.001"):
|
||||
raise ValidationError(f"Question weights must sum to 1.0 (got {total}).")
|
||||
|
||||
questionnaire = Questionnaire(
|
||||
key=payload.key,
|
||||
title=payload.title,
|
||||
description=payload.description,
|
||||
version=payload.version,
|
||||
review_cycle_id=payload.review_cycle_id,
|
||||
)
|
||||
for item in payload.items:
|
||||
questionnaire.items.append(
|
||||
QuestionnaireQuestion(
|
||||
question_id=item.question_id,
|
||||
display_order=item.display_order,
|
||||
weight=item.weight,
|
||||
is_required=item.is_required,
|
||||
)
|
||||
)
|
||||
db.add(questionnaire)
|
||||
db.flush()
|
||||
audit.record(db, action="questionnaire.created", entity_type="questionnaire",
|
||||
entity_id=questionnaire.id, actor_id=actor.id)
|
||||
db.commit()
|
||||
return questionnaire
|
||||
|
||||
|
||||
@router.get("", response_model=list[QuestionnaireOut])
|
||||
def list_questionnaires(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[Questionnaire]:
|
||||
return list(db.scalars(select(Questionnaire).order_by(Questionnaire.key, Questionnaire.version)))
|
||||
|
||||
|
||||
@router.get("/{questionnaire_id}", response_model=QuestionnaireOut)
|
||||
def get_questionnaire(questionnaire_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> Questionnaire:
|
||||
questionnaire = db.get(Questionnaire, questionnaire_id)
|
||||
if questionnaire is None:
|
||||
raise NotFoundError("Questionnaire not found.")
|
||||
return questionnaire
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import get_current_user, require_role
|
||||
from ..enums import UserRole
|
||||
from ..errors import ConflictError, NotFoundError
|
||||
from ..models import AnswerOption, AppUser, Question
|
||||
from ..schemas import QuestionCreate, QuestionOut
|
||||
from ..services import audit
|
||||
|
||||
router = APIRouter(prefix="/questions", tags=["questionnaire"])
|
||||
|
||||
_WRITE = require_role(UserRole.admin, UserRole.legal_ops)
|
||||
|
||||
|
||||
@router.post("", response_model=QuestionOut, status_code=201)
|
||||
def create_question(payload: QuestionCreate, db: Session = Depends(get_db),
|
||||
actor: AppUser = Depends(_WRITE)) -> Question:
|
||||
if db.scalar(select(Question).where(Question.key == payload.key)):
|
||||
raise ConflictError(f"Question key '{payload.key}' already exists.")
|
||||
question = Question(
|
||||
key=payload.key,
|
||||
label=payload.label,
|
||||
help_text=payload.help_text,
|
||||
category=payload.category,
|
||||
answer_type=payload.answer_type,
|
||||
scale_min=payload.scale_min,
|
||||
scale_max=payload.scale_max,
|
||||
)
|
||||
for opt in payload.options:
|
||||
question.options.append(
|
||||
AnswerOption(
|
||||
code=opt.code, label=opt.label, value=opt.value,
|
||||
display_order=opt.display_order, is_active=opt.is_active,
|
||||
)
|
||||
)
|
||||
db.add(question)
|
||||
db.flush()
|
||||
audit.record(db, action="question.created", entity_type="question", entity_id=question.id,
|
||||
actor_id=actor.id)
|
||||
db.commit()
|
||||
return question
|
||||
|
||||
|
||||
@router.get("", response_model=list[QuestionOut])
|
||||
def list_questions(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[Question]:
|
||||
return list(db.scalars(select(Question).order_by(Question.key)))
|
||||
|
||||
|
||||
@router.get("/{question_id}", response_model=QuestionOut)
|
||||
def get_question(question_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> Question:
|
||||
question = db.get(Question, question_id)
|
||||
if question is None:
|
||||
raise NotFoundError("Question not found.")
|
||||
return question
|
||||
@@ -0,0 +1,55 @@
|
||||
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 get_current_user, require_role
|
||||
from ..enums import UserRole
|
||||
from ..errors import AuthorizationError, NotFoundError
|
||||
from ..models import AppUser, Response as ResponseModel
|
||||
from ..schemas import ResponseCreate, ResponseOut, ResponseRevisionOut
|
||||
from ..services import responses as response_service
|
||||
|
||||
router = APIRouter(prefix="/responses", tags=["responses"])
|
||||
|
||||
|
||||
@router.post("", response_model=ResponseOut, status_code=201)
|
||||
def submit_response(
|
||||
payload: ResponseCreate,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(require_role(UserRole.matter_owner)),
|
||||
) -> ResponseModel:
|
||||
"""Create or update an evaluation. Separation of duties: admin/legal_ops cannot score."""
|
||||
ip = request.client.host if request.client else None
|
||||
request_id = request.headers.get("x-request-id")
|
||||
resp = response_service.create_or_update(db, payload, user, ip=ip, request_id=request_id)
|
||||
db.commit()
|
||||
db.refresh(resp)
|
||||
return resp
|
||||
|
||||
|
||||
@router.get("/{response_id}", response_model=ResponseOut)
|
||||
def get_response(response_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> ResponseModel:
|
||||
resp = db.get(ResponseModel, response_id)
|
||||
if resp is None:
|
||||
raise NotFoundError("Response not found.")
|
||||
# Matter owners may only read their own responses.
|
||||
if user.role == UserRole.matter_owner and resp.respondent_id != user.id:
|
||||
raise AuthorizationError("You can only view your own responses.")
|
||||
return resp
|
||||
|
||||
|
||||
@router.get("/{response_id}/history", response_model=list[ResponseRevisionOut])
|
||||
def get_history(response_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)):
|
||||
resp = db.get(ResponseModel, response_id)
|
||||
if resp is None:
|
||||
raise NotFoundError("Response not found.")
|
||||
if user.role == UserRole.matter_owner and resp.respondent_id != user.id:
|
||||
raise AuthorizationError("You can only view your own responses.")
|
||||
return response_service.history(db, response_id)
|
||||
@@ -0,0 +1,91 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import get_current_user, require_role
|
||||
from ..enums import ResponseStatus, ReviewCycleStatus, UserRole
|
||||
from ..errors import ConflictError, NotFoundError
|
||||
from ..models import AppUser, Response, ReviewCycle, ScoreSnapshot
|
||||
from ..schemas import ReviewCycleCreate, ReviewCycleOut, ScoreSnapshotOut
|
||||
from ..services import audit, scoring
|
||||
|
||||
router = APIRouter(prefix="/review-cycles", tags=["review-cycles"])
|
||||
|
||||
_WRITE = require_role(UserRole.admin, UserRole.legal_ops)
|
||||
|
||||
|
||||
@router.post("", response_model=ReviewCycleOut, status_code=201)
|
||||
def create_cycle(payload: ReviewCycleCreate, db: Session = Depends(get_db),
|
||||
actor: AppUser = Depends(_WRITE)) -> ReviewCycle:
|
||||
cycle = ReviewCycle(**payload.model_dump())
|
||||
db.add(cycle)
|
||||
db.flush()
|
||||
audit.record(db, action="review_cycle.created", entity_type="review_cycle",
|
||||
entity_id=cycle.id, actor_id=actor.id)
|
||||
db.commit()
|
||||
return cycle
|
||||
|
||||
|
||||
@router.get("", response_model=list[ReviewCycleOut])
|
||||
def list_cycles(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[ReviewCycle]:
|
||||
return list(db.scalars(select(ReviewCycle).order_by(ReviewCycle.start_date.desc())))
|
||||
|
||||
|
||||
@router.post("/{cycle_id}/close", response_model=list[ScoreSnapshotOut])
|
||||
def close_cycle(cycle_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
actor: AppUser = Depends(_WRITE)) -> list[ScoreSnapshot]:
|
||||
"""Materialize one immutable ScoreSnapshot per firm, lock responses, close the cycle."""
|
||||
cycle = db.get(ReviewCycle, cycle_id)
|
||||
if cycle is None:
|
||||
raise NotFoundError("Review cycle not found.")
|
||||
if cycle.status == ReviewCycleStatus.closed:
|
||||
raise ConflictError("Review cycle is already closed.")
|
||||
|
||||
firm_ids = db.scalars(
|
||||
select(Response.firm_id)
|
||||
.where(Response.review_cycle_id == cycle_id,
|
||||
Response.status == ResponseStatus.submitted,
|
||||
Response.firm_id.is_not(None))
|
||||
.distinct()
|
||||
).all()
|
||||
|
||||
snapshots = [scoring.compute_firm_snapshot(db, fid, cycle_id) for fid in firm_ids]
|
||||
|
||||
# Lock submitted responses so the snapshot inputs are frozen (spec §H.4).
|
||||
for resp in db.scalars(
|
||||
select(Response).where(Response.review_cycle_id == cycle_id,
|
||||
Response.status == ResponseStatus.submitted)
|
||||
):
|
||||
resp.status = ResponseStatus.locked
|
||||
|
||||
cycle.status = ReviewCycleStatus.closed
|
||||
cycle.closed_at = dt.datetime.now(dt.timezone.utc)
|
||||
cycle.closed_by = actor.id
|
||||
audit.record(db, action="review_cycle.closed", entity_type="review_cycle",
|
||||
entity_id=cycle.id, actor_id=actor.id,
|
||||
diff={"firms_scored": len(snapshots)})
|
||||
db.commit()
|
||||
for snap in snapshots:
|
||||
db.refresh(snap)
|
||||
return snapshots
|
||||
|
||||
|
||||
@router.get("/{cycle_id}/snapshots", response_model=list[ScoreSnapshotOut])
|
||||
def cycle_snapshots(cycle_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[ScoreSnapshot]:
|
||||
if db.get(ReviewCycle, cycle_id) is None:
|
||||
raise NotFoundError("Review cycle not found.")
|
||||
return list(
|
||||
db.scalars(
|
||||
select(ScoreSnapshot)
|
||||
.where(ScoreSnapshot.review_cycle_id == cycle_id)
|
||||
.order_by(ScoreSnapshot.composite_score.desc())
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
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 ..schemas import SearchHit, SearchResponse
|
||||
from ..services import search as search_service
|
||||
|
||||
router = APIRouter(prefix="/search", tags=["search"])
|
||||
|
||||
|
||||
@router.get("", response_model=SearchResponse)
|
||||
def full_text_search(
|
||||
q: str = Query(..., min_length=1, description="Search text (PostgreSQL FTS)."),
|
||||
types: str | None = Query(
|
||||
None, description="Comma-separated entity filter: firm,matter,question,response."
|
||||
),
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user),
|
||||
) -> SearchResponse:
|
||||
type_list = [t.strip() for t in types.split(",")] if types else None
|
||||
hits = search_service.search(db, q, types=type_list, limit=limit)
|
||||
return SearchResponse(query=q, hits=[SearchHit(**h) for h in hits])
|
||||
@@ -0,0 +1,72 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import require_role
|
||||
from ..enums import UserRole
|
||||
from ..errors import ConflictError, NotFoundError
|
||||
from ..models import AppUser
|
||||
from ..schemas import UserCreate, UserOut, UserUpdate
|
||||
from ..security import hash_password
|
||||
from ..services import audit
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
@router.post("", response_model=UserOut, status_code=201)
|
||||
def create_user(payload: UserCreate, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_role(UserRole.admin))) -> AppUser:
|
||||
if db.scalar(select(AppUser).where(AppUser.email.ilike(payload.email))):
|
||||
raise ConflictError("A user with that email already exists.")
|
||||
user = AppUser(
|
||||
email=payload.email,
|
||||
full_name=payload.full_name,
|
||||
password_hash=hash_password(payload.password),
|
||||
role=payload.role,
|
||||
)
|
||||
db.add(user)
|
||||
db.flush()
|
||||
audit.record(db, action="user.created", entity_type="app_user", entity_id=user.id,
|
||||
actor_id=admin.id)
|
||||
db.commit()
|
||||
return user
|
||||
|
||||
|
||||
@router.get("", response_model=list[UserOut])
|
||||
def list_users(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(require_role(UserRole.admin))) -> list[AppUser]:
|
||||
return list(db.scalars(select(AppUser).order_by(AppUser.created_at)))
|
||||
|
||||
|
||||
@router.patch("/{user_id}", response_model=UserOut)
|
||||
def update_user(user_id: uuid.UUID, payload: UserUpdate, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_role(UserRole.admin))) -> AppUser:
|
||||
user = db.get(AppUser, user_id)
|
||||
if user is None:
|
||||
raise NotFoundError("User not found.")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
for field, value in data.items():
|
||||
setattr(user, field, value)
|
||||
audit.record(db, action="user.updated", entity_type="app_user", entity_id=user.id,
|
||||
actor_id=admin.id, diff={"changed": list(data.keys())})
|
||||
db.commit()
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/{user_id}/deactivate", response_model=UserOut)
|
||||
def deactivate_user(user_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_role(UserRole.admin))) -> AppUser:
|
||||
"""Immediate offboarding: disable the account (sessions stop validating)."""
|
||||
user = db.get(AppUser, user_id)
|
||||
if user is None:
|
||||
raise NotFoundError("User not found.")
|
||||
user.is_active = False
|
||||
audit.record(db, action="user.deactivated", entity_type="app_user", entity_id=user.id,
|
||||
actor_id=admin.id)
|
||||
db.commit()
|
||||
return user
|
||||
@@ -0,0 +1,299 @@
|
||||
"""Pydantic v2 request/response DTOs. Deliberately separate from ORM models."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field
|
||||
|
||||
from .enums import (
|
||||
AnswerType,
|
||||
ComplexityBand,
|
||||
ConstrainedReason,
|
||||
FirmRankingStatus,
|
||||
FirmStatus,
|
||||
MatterStatus,
|
||||
MatterType,
|
||||
QuestionCategory,
|
||||
QuestionnaireStatus,
|
||||
ResponseStatus,
|
||||
ReviewCycleStatus,
|
||||
UserRole,
|
||||
ValueBand,
|
||||
)
|
||||
|
||||
|
||||
class ORMModel(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
# ─── Auth & users ────────────────────────────────────────────────────────────
|
||||
class LoginRequest(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
class UserCreate(BaseModel):
|
||||
email: EmailStr
|
||||
full_name: str = Field(min_length=1)
|
||||
password: str = Field(min_length=8)
|
||||
role: UserRole = UserRole.matter_owner
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
full_name: str | None = Field(default=None, min_length=1)
|
||||
role: UserRole | None = None
|
||||
is_active: bool | None = None
|
||||
|
||||
|
||||
class UserOut(ORMModel):
|
||||
id: uuid.UUID
|
||||
email: str
|
||||
full_name: str
|
||||
role: UserRole
|
||||
is_active: bool
|
||||
created_at: dt.datetime
|
||||
|
||||
|
||||
class LoginResponse(BaseModel):
|
||||
token: str
|
||||
user: UserOut
|
||||
|
||||
|
||||
# ─── Firms & matters ─────────────────────────────────────────────────────────
|
||||
class FirmCreate(BaseModel):
|
||||
name: str = Field(min_length=1)
|
||||
legal_name: str | None = None
|
||||
website: str | None = None
|
||||
notes: str | None = None
|
||||
status: FirmStatus = FirmStatus.active
|
||||
|
||||
|
||||
class FirmUpdate(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=1)
|
||||
legal_name: str | None = None
|
||||
website: str | None = None
|
||||
notes: str | None = None
|
||||
status: FirmStatus | None = None
|
||||
|
||||
|
||||
class FirmOut(ORMModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
legal_name: str | None
|
||||
status: FirmStatus
|
||||
website: str | None
|
||||
notes: str | None
|
||||
created_at: dt.datetime
|
||||
|
||||
|
||||
class MatterCreate(BaseModel):
|
||||
reference: str = Field(min_length=1)
|
||||
title: str = Field(min_length=1)
|
||||
firm_id: uuid.UUID
|
||||
practice_area_id: uuid.UUID
|
||||
jurisdiction_id: uuid.UUID
|
||||
matter_owner_id: uuid.UUID | None = None # defaults to current user
|
||||
matter_type: MatterType = MatterType.advisory
|
||||
complexity_band: ComplexityBand = ComplexityBand.standard
|
||||
value_band: ValueBand | None = None
|
||||
is_constrained_choice: bool = False
|
||||
constrained_reason: ConstrainedReason | None = None
|
||||
budget_estimate: Decimal | None = None
|
||||
budget_currency: str | None = Field(default=None, min_length=3, max_length=3)
|
||||
|
||||
|
||||
class MatterOut(ORMModel):
|
||||
id: uuid.UUID
|
||||
reference: str
|
||||
title: str
|
||||
firm_id: uuid.UUID
|
||||
practice_area_id: uuid.UUID
|
||||
jurisdiction_id: uuid.UUID
|
||||
matter_owner_id: uuid.UUID
|
||||
matter_type: MatterType
|
||||
complexity_band: ComplexityBand
|
||||
value_band: ValueBand | None
|
||||
is_constrained_choice: bool
|
||||
status: MatterStatus
|
||||
created_at: dt.datetime
|
||||
|
||||
|
||||
# ─── Questionnaire engine ────────────────────────────────────────────────────
|
||||
class AnswerOptionIn(BaseModel):
|
||||
code: str = Field(min_length=1)
|
||||
label: str = Field(min_length=1)
|
||||
value: Decimal | None = None
|
||||
display_order: int = 0
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class AnswerOptionOut(ORMModel):
|
||||
id: uuid.UUID
|
||||
code: str
|
||||
label: str
|
||||
value: Decimal | None
|
||||
display_order: int
|
||||
is_active: bool
|
||||
|
||||
|
||||
class QuestionCreate(BaseModel):
|
||||
key: str = Field(min_length=1)
|
||||
label: str = Field(min_length=1)
|
||||
help_text: str | None = None
|
||||
category: QuestionCategory = QuestionCategory.qualitative
|
||||
answer_type: AnswerType = AnswerType.scale
|
||||
scale_min: int = 1
|
||||
scale_max: int = 5
|
||||
options: list[AnswerOptionIn] = Field(default_factory=list)
|
||||
|
||||
|
||||
class QuestionOut(ORMModel):
|
||||
id: uuid.UUID
|
||||
key: str
|
||||
label: str
|
||||
help_text: str | None
|
||||
category: QuestionCategory
|
||||
answer_type: AnswerType
|
||||
scale_min: int
|
||||
scale_max: int
|
||||
is_active: bool
|
||||
options: list[AnswerOptionOut] = Field(default_factory=list)
|
||||
|
||||
|
||||
class QuestionnaireItemIn(BaseModel):
|
||||
question_id: uuid.UUID
|
||||
display_order: int = 0
|
||||
weight: Decimal = Decimal("0")
|
||||
is_required: bool = True
|
||||
|
||||
|
||||
class QuestionnaireItemOut(ORMModel):
|
||||
question_id: uuid.UUID
|
||||
display_order: int
|
||||
weight: Decimal
|
||||
is_required: bool
|
||||
|
||||
|
||||
class QuestionnaireCreate(BaseModel):
|
||||
key: str = Field(min_length=1)
|
||||
title: str = Field(min_length=1)
|
||||
description: str | None = None
|
||||
version: int = 1
|
||||
review_cycle_id: uuid.UUID | None = None
|
||||
items: list[QuestionnaireItemIn] = Field(default_factory=list)
|
||||
|
||||
|
||||
class QuestionnaireOut(ORMModel):
|
||||
id: uuid.UUID
|
||||
key: str
|
||||
title: str
|
||||
description: str | None
|
||||
status: QuestionnaireStatus
|
||||
version: int
|
||||
review_cycle_id: uuid.UUID | None
|
||||
items: list[QuestionnaireItemOut] = Field(default_factory=list)
|
||||
|
||||
|
||||
# ─── Responses (results) + history ───────────────────────────────────────────
|
||||
class ResponseItemIn(BaseModel):
|
||||
question_id: uuid.UUID
|
||||
answer_option_id: uuid.UUID | None = None
|
||||
numeric_value: Decimal | None = None
|
||||
bool_value: bool | None = None
|
||||
text_value: str | None = None
|
||||
comment: str | None = None
|
||||
|
||||
|
||||
class ResponseItemOut(ORMModel):
|
||||
question_id: uuid.UUID
|
||||
answer_option_id: uuid.UUID | None
|
||||
numeric_value: Decimal | None
|
||||
bool_value: bool | None
|
||||
text_value: str | None
|
||||
comment: str | None
|
||||
|
||||
|
||||
class ResponseCreate(BaseModel):
|
||||
questionnaire_id: uuid.UUID
|
||||
matter_id: uuid.UUID | None = None
|
||||
firm_id: uuid.UUID | None = None
|
||||
review_cycle_id: uuid.UUID | None = None
|
||||
recommend: bool | None = None
|
||||
is_constrained: bool = False
|
||||
overall_comment: str | None = Field(default=None, max_length=280)
|
||||
submit: bool = False # false → save draft, true → submit
|
||||
items: list[ResponseItemIn] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ResponseOut(ORMModel):
|
||||
id: uuid.UUID
|
||||
questionnaire_id: uuid.UUID
|
||||
respondent_ref: uuid.UUID
|
||||
matter_id: uuid.UUID | None
|
||||
firm_id: uuid.UUID | None
|
||||
review_cycle_id: uuid.UUID | None
|
||||
status: ResponseStatus
|
||||
recommend: bool | None
|
||||
is_constrained: bool
|
||||
overall_comment: str | None
|
||||
score: Decimal | None
|
||||
revision: int
|
||||
submitted_at: dt.datetime | None
|
||||
items: list[ResponseItemOut] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ResponseRevisionOut(ORMModel):
|
||||
revision_no: int
|
||||
snapshot: dict
|
||||
change_reason: str | None
|
||||
created_at: dt.datetime
|
||||
|
||||
|
||||
# ─── Review cycles & snapshots ───────────────────────────────────────────────
|
||||
class ReviewCycleCreate(BaseModel):
|
||||
name: str = Field(min_length=1)
|
||||
start_date: dt.date
|
||||
end_date: dt.date
|
||||
min_evaluations: int = 3
|
||||
|
||||
|
||||
class ReviewCycleOut(ORMModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
start_date: dt.date
|
||||
end_date: dt.date
|
||||
status: ReviewCycleStatus
|
||||
min_evaluations: int
|
||||
|
||||
|
||||
class ScoreSnapshotOut(ORMModel):
|
||||
id: uuid.UUID
|
||||
firm_id: uuid.UUID
|
||||
review_cycle_id: uuid.UUID
|
||||
composite_score: Decimal
|
||||
qualitative_score: Decimal | None
|
||||
quantitative_score: Decimal | None
|
||||
data_completeness: Decimal | None
|
||||
evaluation_count: int
|
||||
ranking_status: FirmRankingStatus
|
||||
breakdown: dict | None
|
||||
computed_at: dt.datetime
|
||||
|
||||
|
||||
# ─── Search ──────────────────────────────────────────────────────────────────
|
||||
class SearchHit(BaseModel):
|
||||
type: str
|
||||
id: str
|
||||
title: str | None
|
||||
rank: float
|
||||
|
||||
|
||||
class SearchResponse(BaseModel):
|
||||
query: str
|
||||
hits: list[SearchHit]
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Password hashing (Argon2id) and opaque session-token helpers."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
|
||||
# Spec §I.3 starting parameters.
|
||||
_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 needs_rehash(password_hash: str) -> bool:
|
||||
return _hasher.check_needs_rehash(password_hash)
|
||||
|
||||
|
||||
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 instant kill-switch."""
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Idempotent seed: dictionaries, the canonical 8 criteria as questions + answers,
|
||||
a default evaluation questionnaire, an open review cycle, and the bootstrap admin.
|
||||
|
||||
Run after migrations (the compose `migrate` service does this automatically):
|
||||
python -m app.seed
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import logging
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .config import get_settings
|
||||
from .enums import (
|
||||
AnswerType,
|
||||
QuestionCategory,
|
||||
QuestionnaireStatus,
|
||||
ReviewCycleStatus,
|
||||
UserRole,
|
||||
)
|
||||
from .models import (
|
||||
AnswerOption,
|
||||
AppSetting,
|
||||
AppUser,
|
||||
Jurisdiction,
|
||||
PracticeArea,
|
||||
Question,
|
||||
Questionnaire,
|
||||
QuestionnaireQuestion,
|
||||
ReviewCycle,
|
||||
)
|
||||
from .security import hash_password
|
||||
|
||||
logger = logging.getLogger("seed")
|
||||
settings = get_settings()
|
||||
|
||||
PRACTICE_AREAS = [
|
||||
("m_and_a", "M&A"),
|
||||
("litigation", "Litigation"),
|
||||
("ip", "Intellectual Property"),
|
||||
("employment", "Employment"),
|
||||
("data_protection", "Data Protection"),
|
||||
("regulatory", "Regulatory"),
|
||||
]
|
||||
|
||||
JURISDICTIONS = [
|
||||
("PL", "Poland"),
|
||||
("DE", "Germany"),
|
||||
("FR", "France"),
|
||||
("US", "United States"),
|
||||
("GB", "United Kingdom"),
|
||||
("JP", "Japan"),
|
||||
]
|
||||
|
||||
# 1-5 anchors shared by every qualitative question (spec §F.2).
|
||||
QUAL_ANCHORS = [
|
||||
("5", "Wzorowo — postawiłbym to jako benchmark.", 5),
|
||||
("4", "Dobrze — drobne uwagi, chętnie dam kolejny matter.", 4),
|
||||
("3", "OK — zrobili robotę, nic nie wyróżnia.", 3),
|
||||
("2", "Słabo — konkretne problemy, kosztowały mnie czas.", 2),
|
||||
("1", "Źle — nie chcę ich na podobnym matterze.", 1),
|
||||
]
|
||||
|
||||
# key, label, category, answer_type, default weight (sum across all 8 = 1.00).
|
||||
QUESTIONS = [
|
||||
("quality_of_advice", "Jakość porady", QuestionCategory.qualitative, AnswerType.scale, "0.25"),
|
||||
("responsiveness", "Responsywność", QuestionCategory.qualitative, AnswerType.scale, "0.15"),
|
||||
("client_management", "Prowadzenie sprawy", QuestionCategory.qualitative, AnswerType.scale, "0.10"),
|
||||
("scope_control", "Kontrola zakresu", QuestionCategory.qualitative, AnswerType.scale, "0.15"),
|
||||
("commerciality", "Komercyjność", QuestionCategory.qualitative, AnswerType.scale, "0.10"),
|
||||
("budget_adherence", "Trzymanie budżetu", QuestionCategory.quantitative, AnswerType.numeric, "0.10"),
|
||||
("billing_hygiene", "Higiena rozliczeń", QuestionCategory.quantitative, AnswerType.numeric, "0.10"),
|
||||
("effective_rate", "Efektywna stawka", QuestionCategory.quantitative, AnswerType.numeric, "0.05"),
|
||||
]
|
||||
|
||||
QUESTIONNAIRE_KEY = "counsel_evaluation"
|
||||
|
||||
|
||||
def _get_or_create(db: Session, model, *, defaults: dict | None = None, **filters):
|
||||
instance = db.scalar(select(model).filter_by(**filters))
|
||||
if instance is not None:
|
||||
return instance, False
|
||||
instance = model(**filters, **(defaults or {}))
|
||||
db.add(instance)
|
||||
db.flush()
|
||||
return instance, True
|
||||
|
||||
|
||||
def seed(db: Session) -> None:
|
||||
# Instance settings
|
||||
if db.get(AppSetting, "base_currency") is None:
|
||||
db.add(AppSetting(key="base_currency", value=settings.base_currency))
|
||||
|
||||
for code, label in PRACTICE_AREAS:
|
||||
_get_or_create(db, PracticeArea, code=code, defaults={"label": label})
|
||||
for code, label in JURISDICTIONS:
|
||||
_get_or_create(db, Jurisdiction, code=code, defaults={"label": label})
|
||||
|
||||
# Questions + answer options
|
||||
questions: dict[str, Question] = {}
|
||||
for key, label, category, answer_type, _weight in QUESTIONS:
|
||||
q, created = _get_or_create(
|
||||
db, Question, key=key,
|
||||
defaults={"label": label, "category": category, "answer_type": answer_type},
|
||||
)
|
||||
questions[key] = q
|
||||
if created and answer_type == AnswerType.scale:
|
||||
for code, text, value in QUAL_ANCHORS:
|
||||
db.add(
|
||||
AnswerOption(
|
||||
question_id=q.id, code=code, label=text,
|
||||
value=Decimal(value), display_order=6 - value,
|
||||
)
|
||||
)
|
||||
|
||||
# Open review cycle
|
||||
cycle = db.scalar(select(ReviewCycle).where(ReviewCycle.status == ReviewCycleStatus.open))
|
||||
if cycle is None:
|
||||
today = dt.date(2026, 4, 1)
|
||||
cycle = ReviewCycle(name="Q2 2026", start_date=today, end_date=dt.date(2026, 6, 30))
|
||||
db.add(cycle)
|
||||
db.flush()
|
||||
|
||||
# Default questionnaire (all 8 criteria, weights sum to 1.0)
|
||||
questionnaire = db.scalar(
|
||||
select(Questionnaire).where(Questionnaire.key == QUESTIONNAIRE_KEY,
|
||||
Questionnaire.version == 1)
|
||||
)
|
||||
if questionnaire is None:
|
||||
questionnaire = Questionnaire(
|
||||
key=QUESTIONNAIRE_KEY,
|
||||
title="Counsel Evaluation",
|
||||
description="Standardowy formularz oceny kancelarii po zamknięciu sprawy.",
|
||||
status=QuestionnaireStatus.active,
|
||||
version=1,
|
||||
review_cycle_id=cycle.id,
|
||||
)
|
||||
db.add(questionnaire)
|
||||
db.flush()
|
||||
for order, (key, _l, _c, _a, weight) in enumerate(QUESTIONS):
|
||||
db.add(
|
||||
QuestionnaireQuestion(
|
||||
questionnaire_id=questionnaire.id,
|
||||
question_id=questions[key].id,
|
||||
display_order=order,
|
||||
weight=Decimal(weight),
|
||||
is_required=questions[key].category == QuestionCategory.qualitative,
|
||||
)
|
||||
)
|
||||
|
||||
# Bootstrap admin
|
||||
admin = db.scalar(select(AppUser).where(AppUser.email.ilike(settings.bootstrap_admin_email)))
|
||||
if admin is None:
|
||||
db.add(
|
||||
AppUser(
|
||||
email=settings.bootstrap_admin_email,
|
||||
full_name="Bootstrap Admin",
|
||||
password_hash=hash_password(settings.bootstrap_admin_password),
|
||||
role=UserRole.admin,
|
||||
)
|
||||
)
|
||||
|
||||
db.commit()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
engine = create_engine(settings.migration_database_url, future=True)
|
||||
with Session(engine) as db:
|
||||
seed(db)
|
||||
logger.info("Seed complete.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
"""Domain services: business logic, orchestration, audit. No HTTP, no raw SQL building leaks."""
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Append-only audit logging (spec §H.2 audit_log)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import AuditLog
|
||||
|
||||
|
||||
def record(
|
||||
db: Session,
|
||||
*,
|
||||
action: str,
|
||||
entity_type: str,
|
||||
entity_id: uuid.UUID,
|
||||
actor_id: uuid.UUID | None = None,
|
||||
result: str = "success",
|
||||
ip: str | None = None,
|
||||
request_id: str | None = None,
|
||||
diff: dict | None = None,
|
||||
) -> None:
|
||||
"""Insert an audit row. Does not commit — the caller's transaction owns it."""
|
||||
db.add(
|
||||
AuditLog(
|
||||
actor_id=actor_id,
|
||||
action=action,
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
result=result,
|
||||
ip=ip,
|
||||
request_id=request_id,
|
||||
diff=diff,
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Authentication: credential check + server-side sessions (instant kill-switch)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..config import get_settings
|
||||
from ..models import AppUser, Session
|
||||
from ..security import generate_session_token, hash_token, verify_password
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
def authenticate(db: DbSession, email: str, password: str) -> AppUser | None:
|
||||
user = db.scalar(select(AppUser).where(AppUser.email.ilike(email)))
|
||||
if user is None or not user.is_active:
|
||||
return None
|
||||
if not verify_password(password, user.password_hash):
|
||||
return 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, refreshing last_seen_at. 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
|
||||
session.last_seen_at = now
|
||||
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)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Response lifecycle: draft/submit, scoring, and append-only revision history."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..enums import ResponseStatus
|
||||
from ..errors import ConflictError, NotFoundError
|
||||
from ..models import AppUser, Matter, Response, ResponseItem, ResponseRevision
|
||||
from ..schemas import ResponseCreate
|
||||
from . import audit, scoring
|
||||
|
||||
# Fixed namespace for deriving a stable, pseudonymous reviewer reference.
|
||||
_REF_NAMESPACE = uuid.UUID("c0c0c0c0-0000-4000-8000-000000000001")
|
||||
|
||||
|
||||
def _respondent_ref(user_id: uuid.UUID, matter_id: uuid.UUID | None,
|
||||
questionnaire_id: uuid.UUID) -> uuid.UUID:
|
||||
seed = f"{user_id}:{matter_id or questionnaire_id}"
|
||||
return uuid.uuid5(_REF_NAMESPACE, seed)
|
||||
|
||||
|
||||
def _snapshot(resp: Response) -> dict:
|
||||
return {
|
||||
"status": resp.status.value,
|
||||
"score": float(resp.score) if resp.score is not None else None,
|
||||
"recommend": resp.recommend,
|
||||
"is_constrained": resp.is_constrained,
|
||||
"overall_comment": resp.overall_comment,
|
||||
"items": [
|
||||
{
|
||||
"question_id": str(it.question_id),
|
||||
"answer_option_id": str(it.answer_option_id) if it.answer_option_id else None,
|
||||
"numeric_value": float(it.numeric_value) if it.numeric_value is not None else None,
|
||||
"bool_value": it.bool_value,
|
||||
"text_value": it.text_value,
|
||||
"comment": it.comment,
|
||||
}
|
||||
for it in resp.items
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def create_or_update(db: Session, payload: ResponseCreate, user: AppUser,
|
||||
*, ip: str | None = None, request_id: str | None = None) -> Response:
|
||||
ref = _respondent_ref(user.id, payload.matter_id, payload.questionnaire_id)
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
|
||||
# Derive firm from matter when not supplied explicitly.
|
||||
firm_id = payload.firm_id
|
||||
if payload.matter_id is not None:
|
||||
matter = db.get(Matter, payload.matter_id)
|
||||
if matter is None:
|
||||
raise NotFoundError("Matter not found.")
|
||||
if matter.matter_owner_id != user.id and user.role.value != "admin":
|
||||
raise ConflictError("You can only evaluate your own matters.")
|
||||
firm_id = firm_id or matter.firm_id
|
||||
|
||||
resp = db.scalar(
|
||||
select(Response).where(
|
||||
Response.questionnaire_id == payload.questionnaire_id,
|
||||
Response.matter_id == payload.matter_id,
|
||||
Response.respondent_ref == ref,
|
||||
)
|
||||
)
|
||||
creating = resp is None
|
||||
if creating:
|
||||
resp = Response(
|
||||
questionnaire_id=payload.questionnaire_id,
|
||||
respondent_id=user.id,
|
||||
respondent_ref=ref,
|
||||
matter_id=payload.matter_id,
|
||||
opened_at=now,
|
||||
revision=0,
|
||||
)
|
||||
db.add(resp)
|
||||
elif resp.status == ResponseStatus.locked:
|
||||
raise ConflictError("Response is locked (cycle closed) and cannot be edited.")
|
||||
|
||||
resp.firm_id = firm_id
|
||||
resp.review_cycle_id = payload.review_cycle_id
|
||||
resp.recommend = payload.recommend
|
||||
resp.is_constrained = payload.is_constrained
|
||||
resp.overall_comment = payload.overall_comment
|
||||
|
||||
# Replace items wholesale (simplest correct semantics for a full form submit).
|
||||
resp.items.clear()
|
||||
db.flush()
|
||||
for item in payload.items:
|
||||
resp.items.append(
|
||||
ResponseItem(
|
||||
question_id=item.question_id,
|
||||
answer_option_id=item.answer_option_id,
|
||||
numeric_value=item.numeric_value,
|
||||
bool_value=item.bool_value,
|
||||
text_value=item.text_value,
|
||||
comment=item.comment,
|
||||
)
|
||||
)
|
||||
db.flush()
|
||||
|
||||
resp.score = scoring.compute_response_score(db, resp)
|
||||
resp.status = ResponseStatus.submitted if payload.submit else ResponseStatus.draft
|
||||
if payload.submit:
|
||||
resp.submitted_at = now
|
||||
resp.revision = (resp.revision or 0) + 1
|
||||
db.flush()
|
||||
|
||||
db.add(
|
||||
ResponseRevision(
|
||||
response_id=resp.id,
|
||||
revision_no=resp.revision,
|
||||
snapshot=_snapshot(resp),
|
||||
changed_by=user.id,
|
||||
change_reason="submit" if payload.submit else "draft",
|
||||
)
|
||||
)
|
||||
audit.record(
|
||||
db,
|
||||
action="response.submitted" if payload.submit else "response.saved",
|
||||
entity_type="response",
|
||||
entity_id=resp.id,
|
||||
actor_id=user.id,
|
||||
ip=ip,
|
||||
request_id=request_id,
|
||||
)
|
||||
return resp
|
||||
|
||||
|
||||
def history(db: Session, response_id: uuid.UUID) -> list[ResponseRevision]:
|
||||
if db.get(Response, response_id) is None:
|
||||
raise NotFoundError("Response not found.")
|
||||
return list(
|
||||
db.scalars(
|
||||
select(ResponseRevision)
|
||||
.where(ResponseRevision.response_id == response_id)
|
||||
.order_by(ResponseRevision.revision_no.desc())
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Composite scoring (spec §F.3, present_i model).
|
||||
|
||||
score = ( Σ wᵢ·Cᵢ·presentᵢ / Σ wᵢ·presentᵢ ) × 20
|
||||
|
||||
Cᵢ is a criterion value on the 1-5 scale; presentᵢ re-normalizes the denominator so
|
||||
missing data neither imputes zero nor penalizes a firm. ×20 rescales 1-5 → 0-100.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..enums import FirmRankingStatus, ResponseStatus
|
||||
from ..models import (
|
||||
AnswerOption,
|
||||
Questionnaire,
|
||||
QuestionnaireQuestion,
|
||||
Response,
|
||||
ResponseItem,
|
||||
ScoreSnapshot,
|
||||
)
|
||||
|
||||
SCALE_TO_100 = Decimal(20) # for a 1-5 scale
|
||||
|
||||
|
||||
def _question_weights(db: Session, questionnaire_id: uuid.UUID) -> dict[uuid.UUID, Decimal]:
|
||||
rows = db.execute(
|
||||
select(QuestionnaireQuestion.question_id, QuestionnaireQuestion.weight).where(
|
||||
QuestionnaireQuestion.questionnaire_id == questionnaire_id
|
||||
)
|
||||
).all()
|
||||
return {qid: Decimal(str(w)) for qid, w in rows}
|
||||
|
||||
|
||||
def _item_values(db: Session, response_id: uuid.UUID) -> dict[uuid.UUID, Decimal]:
|
||||
"""question_id → numeric value, preferring explicit numeric_value, else the option's value."""
|
||||
rows = db.execute(
|
||||
select(
|
||||
ResponseItem.question_id,
|
||||
ResponseItem.numeric_value,
|
||||
AnswerOption.value,
|
||||
)
|
||||
.select_from(ResponseItem)
|
||||
.join(AnswerOption, AnswerOption.id == ResponseItem.answer_option_id, isouter=True)
|
||||
.where(ResponseItem.response_id == response_id)
|
||||
).all()
|
||||
values: dict[uuid.UUID, Decimal] = {}
|
||||
for question_id, numeric_value, option_value in rows:
|
||||
val = numeric_value if numeric_value is not None else option_value
|
||||
if val is not None:
|
||||
values[question_id] = Decimal(str(val))
|
||||
return values
|
||||
|
||||
|
||||
def compute_response_score(db: Session, response: Response) -> Decimal | None:
|
||||
"""Weighted 0-100 score for a single response (present_i over its questionnaire)."""
|
||||
weights = _question_weights(db, response.questionnaire_id)
|
||||
values = _item_values(db, response.id)
|
||||
num = Decimal(0)
|
||||
den = Decimal(0)
|
||||
for qid, weight in weights.items():
|
||||
if weight <= 0 or qid not in values:
|
||||
continue
|
||||
num += weight * values[qid]
|
||||
den += weight
|
||||
if den == 0:
|
||||
return None
|
||||
return (num / den * SCALE_TO_100).quantize(Decimal("0.01"))
|
||||
|
||||
|
||||
def compute_firm_snapshot(
|
||||
db: Session, firm_id: uuid.UUID, review_cycle_id: uuid.UUID
|
||||
) -> ScoreSnapshot:
|
||||
"""Aggregate all submitted, non-constrained responses for a firm in a cycle, upsert snapshot.
|
||||
|
||||
Constrained-choice responses are excluded from the ranking composite (spec §F.3.1).
|
||||
"""
|
||||
responses = list(
|
||||
db.scalars(
|
||||
select(Response).where(
|
||||
Response.firm_id == firm_id,
|
||||
Response.review_cycle_id == review_cycle_id,
|
||||
Response.status == ResponseStatus.submitted,
|
||||
Response.is_constrained.is_(False),
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# Per-question accumulators across all responses.
|
||||
per_q_sum: dict[uuid.UUID, Decimal] = {}
|
||||
per_q_n: dict[uuid.UUID, int] = {}
|
||||
questionnaire_ids: set[uuid.UUID] = set()
|
||||
for resp in responses:
|
||||
questionnaire_ids.add(resp.questionnaire_id)
|
||||
for qid, val in _item_values(db, resp.id).items():
|
||||
per_q_sum[qid] = per_q_sum.get(qid, Decimal(0)) + val
|
||||
per_q_n[qid] = per_q_n.get(qid, 0) + 1
|
||||
|
||||
# Weights from the questionnaire(s) in play (typically one per cycle).
|
||||
weights: dict[uuid.UUID, Decimal] = {}
|
||||
for qn_id in questionnaire_ids:
|
||||
for qid, w in _question_weights(db, qn_id).items():
|
||||
weights[qid] = w
|
||||
|
||||
num = Decimal(0)
|
||||
den = Decimal(0)
|
||||
breakdown_criteria: list[dict] = []
|
||||
weight_present = Decimal(0)
|
||||
weight_total = sum(weights.values()) or Decimal(0)
|
||||
for qid, weight in weights.items():
|
||||
n = per_q_n.get(qid, 0)
|
||||
present = 1 if (n > 0 and weight > 0) else 0
|
||||
c_value = (per_q_sum[qid] / n) if n > 0 else None
|
||||
if present:
|
||||
num += weight * c_value
|
||||
den += weight
|
||||
weight_present += weight
|
||||
breakdown_criteria.append(
|
||||
{
|
||||
"question_id": str(qid),
|
||||
"weight": float(weight),
|
||||
"n": n,
|
||||
"present": present,
|
||||
"avg_1_5": float(c_value) if c_value is not None else None,
|
||||
}
|
||||
)
|
||||
|
||||
composite = (num / den * SCALE_TO_100).quantize(Decimal("0.01")) if den > 0 else Decimal(0)
|
||||
completeness = (
|
||||
(weight_present / weight_total).quantize(Decimal("0.0001"))
|
||||
if weight_total > 0
|
||||
else Decimal(0)
|
||||
)
|
||||
|
||||
snapshot = db.scalar(
|
||||
select(ScoreSnapshot).where(
|
||||
ScoreSnapshot.firm_id == firm_id,
|
||||
ScoreSnapshot.review_cycle_id == review_cycle_id,
|
||||
)
|
||||
)
|
||||
if snapshot is None:
|
||||
snapshot = ScoreSnapshot(firm_id=firm_id, review_cycle_id=review_cycle_id)
|
||||
db.add(snapshot)
|
||||
|
||||
snapshot.composite_score = composite
|
||||
snapshot.qualitative_score = composite # MVP-0: quantitative criteria absent → present=0
|
||||
snapshot.quantitative_score = None
|
||||
snapshot.data_completeness = completeness
|
||||
snapshot.evaluation_count = len(responses)
|
||||
snapshot.invoice_count = 0
|
||||
snapshot.ranking_status = _ranking_status(composite, len(responses))
|
||||
snapshot.breakdown = {"criteria": breakdown_criteria}
|
||||
snapshot.computed_at = dt.datetime.now(dt.timezone.utc)
|
||||
db.flush()
|
||||
return snapshot
|
||||
|
||||
|
||||
def _ranking_status(composite: Decimal, n: int) -> FirmRankingStatus:
|
||||
"""Coarse status bands (spec §F.4 thresholds are configurable; these are sane defaults)."""
|
||||
if n == 0:
|
||||
return FirmRankingStatus.provisional
|
||||
if composite >= 85:
|
||||
return FirmRankingStatus.top_performer
|
||||
if composite >= 70:
|
||||
return FirmRankingStatus.solid
|
||||
if composite >= 55:
|
||||
return FirmRankingStatus.watch
|
||||
if composite >= 40:
|
||||
return FirmRankingStatus.at_risk
|
||||
return FirmRankingStatus.remove_candidate
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Full-text search over the generated tsvector columns (PostgreSQL FTS).
|
||||
|
||||
Primary path: websearch_to_tsquery + ts_rank against GIN-indexed tsvector columns.
|
||||
Fallback: pg_trgm similarity on names/titles when FTS yields nothing (typo tolerance).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Firm, Matter, Question, Response
|
||||
|
||||
# entity_type → (model, id_col, title_col, tsvector_col, fuzzy_col)
|
||||
_ENTITIES = {
|
||||
"firm": (Firm, Firm.id, Firm.name, Firm.search_vector, Firm.name),
|
||||
"matter": (Matter, Matter.id, Matter.title, Matter.search_vector, Matter.title),
|
||||
"question": (Question, Question.id, Question.label, Question.search_vector, Question.label),
|
||||
"response": (Response, Response.id, Response.overall_comment, Response.search_vector, None),
|
||||
}
|
||||
|
||||
|
||||
def search(
|
||||
db: Session, query: str, *, types: list[str] | None = None, limit: int = 20
|
||||
) -> list[dict]:
|
||||
query = (query or "").strip()
|
||||
if not query:
|
||||
return []
|
||||
wanted = [t for t in (types or _ENTITIES.keys()) if t in _ENTITIES]
|
||||
tsq = func.websearch_to_tsquery("simple", query)
|
||||
hits: list[dict] = []
|
||||
|
||||
for etype in wanted:
|
||||
model, id_col, title_col, tsv_col, fuzzy_col = _ENTITIES[etype]
|
||||
rank = func.ts_rank(tsv_col, tsq)
|
||||
stmt = (
|
||||
select(id_col, title_col, rank.label("rank"))
|
||||
.where(tsv_col.op("@@")(tsq))
|
||||
.order_by(rank.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
rows = db.execute(stmt).all()
|
||||
|
||||
# Typo-tolerant fallback for name-like fields when FTS finds nothing.
|
||||
if not rows and fuzzy_col is not None:
|
||||
sim = func.similarity(fuzzy_col, query)
|
||||
stmt = (
|
||||
select(id_col, title_col, sim.label("rank"))
|
||||
.where(sim > 0.2)
|
||||
.order_by(sim.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
rows = db.execute(stmt).all()
|
||||
|
||||
for _id, title, score in rows:
|
||||
hits.append(
|
||||
{
|
||||
"type": etype,
|
||||
"id": str(_id),
|
||||
"title": title,
|
||||
"rank": round(float(score), 5) if score is not None else 0.0,
|
||||
}
|
||||
)
|
||||
|
||||
hits.sort(key=lambda h: h["rank"], reverse=True)
|
||||
return hits[:limit]
|
||||
@@ -0,0 +1,16 @@
|
||||
[project]
|
||||
name = "counsel-scorecard-backend"
|
||||
version = "0.1.0"
|
||||
description = "Counsel Scorecard — backend (FastAPI) for the external-counsel scoring platform."
|
||||
requires-python = ">=3.12"
|
||||
license = { text = "Apache-2.0" }
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
@@ -0,0 +1,24 @@
|
||||
# Web framework
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
python-multipart==0.0.18
|
||||
|
||||
# Validation / settings
|
||||
pydantic==2.10.4
|
||||
pydantic-settings==2.7.1
|
||||
email-validator==2.2.0
|
||||
|
||||
# DB / ORM / migrations
|
||||
SQLAlchemy==2.0.36
|
||||
alembic==1.14.0
|
||||
psycopg[binary]==3.2.3
|
||||
|
||||
# Auth
|
||||
argon2-cffi==23.1.0
|
||||
|
||||
# OpenTelemetry (OTLP → OTel Collector)
|
||||
opentelemetry-sdk==1.29.0
|
||||
opentelemetry-exporter-otlp-proto-grpc==1.29.0
|
||||
opentelemetry-instrumentation-fastapi==0.50b0
|
||||
opentelemetry-instrumentation-sqlalchemy==0.50b0
|
||||
opentelemetry-instrumentation-logging==0.50b0
|
||||
@@ -0,0 +1,28 @@
|
||||
"""DB-free smoke tests (CI-friendly). Deeper tests need a Postgres fixture."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.schemas import ResponseCreate
|
||||
from app.seed import QUESTIONS
|
||||
from app.services.responses import _respondent_ref
|
||||
|
||||
|
||||
def test_seed_weights_sum_to_one():
|
||||
assert sum(Decimal(w) for *_, w in QUESTIONS) == Decimal("1.00")
|
||||
|
||||
|
||||
def test_respondent_ref_is_deterministic_and_pseudonymous():
|
||||
user, matter, qn = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||
a = _respondent_ref(user, matter, qn)
|
||||
b = _respondent_ref(user, matter, qn)
|
||||
assert a == b # stable → enforces one response per reviewer per matter
|
||||
assert a != _respondent_ref(uuid.uuid4(), matter, qn) # differs by reviewer
|
||||
|
||||
|
||||
def test_overall_comment_is_capped_at_280():
|
||||
with pytest.raises(Exception):
|
||||
ResponseCreate(questionnaire_id=uuid.uuid4(), overall_comment="x" * 281)
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Runs once as the superuser against POSTGRES_DB, before the app starts.
|
||||
-- gen_random_uuid() is built into PostgreSQL 13+ core (no extension needed).
|
||||
|
||||
-- Trigram index support for fuzzy / "did you mean" search alongside FTS.
|
||||
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||
|
||||
-- Lets a single GIN index combine a tsvector with scalar columns if desired.
|
||||
CREATE EXTENSION IF NOT EXISTS btree_gin;
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
# Creates least-privilege DB roles (spec §K.1):
|
||||
# migrator → owns DDL (CREATE/ALTER/DROP), used only by the one-shot migrate service
|
||||
# app → runtime role, DML only (SELECT/INSERT/UPDATE/DELETE), never DDL
|
||||
#
|
||||
# Default privileges ensure every table/sequence the migrator creates later
|
||||
# automatically grants DML to app — so the migration never has to GRANT per table.
|
||||
# The audit_log append-only restriction (REVOKE UPDATE/DELETE from app) is applied
|
||||
# inside the Alembic migration, since the table does not exist yet here.
|
||||
set -e
|
||||
|
||||
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
|
||||
CREATE ROLE migrator LOGIN PASSWORD '${DB_MIGRATOR_PASSWORD}';
|
||||
CREATE ROLE app LOGIN PASSWORD '${DB_APP_PASSWORD}';
|
||||
|
||||
GRANT CONNECT ON DATABASE ${POSTGRES_DB} TO migrator, app;
|
||||
GRANT USAGE ON SCHEMA public TO migrator, app;
|
||||
GRANT CREATE ON SCHEMA public TO migrator;
|
||||
|
||||
ALTER DEFAULT PRIVILEGES FOR ROLE migrator IN SCHEMA public
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app;
|
||||
ALTER DEFAULT PRIVILEGES FOR ROLE migrator IN SCHEMA public
|
||||
GRANT USAGE, SELECT ON SEQUENCES TO app;
|
||||
EOSQL
|
||||
@@ -0,0 +1,90 @@
|
||||
# Observability stack — set "S3" from the spec: OTel Collector → ClickHouse → HyperDX.
|
||||
# All Apache-2.0 / MIT, fully self-hosted, no phone-home (gate-clean).
|
||||
#
|
||||
# Run together with the app stack:
|
||||
# docker compose -f docker-compose.yml -f docker-compose.observability.yml up -d --build
|
||||
# Then set OTEL_ENABLED=true in .env so the backend exports OTLP to otel-collector:4317.
|
||||
#
|
||||
# HyperDX UI: http://localhost:8080
|
||||
# On first launch, add a ClickHouse source pointing at clickhouse:8123 (database "otel",
|
||||
# tables otel_traces / otel_logs / otel_metrics). MongoDB below is HyperDX's own metadata
|
||||
# store — it holds no Counsel Scorecard data.
|
||||
#
|
||||
# Lighter alternative (one container, zero config): replace clickhouse + otel-collector +
|
||||
# hyperdx + mongo with the bundled image `hyperdx/hyperdx-all-in-one` (OTLP on 4317/4318,
|
||||
# UI on 8080). See README "Observability".
|
||||
|
||||
networks:
|
||||
internal:
|
||||
observability:
|
||||
|
||||
volumes:
|
||||
ch_data:
|
||||
ch_logs:
|
||||
hdx_mongo:
|
||||
|
||||
services:
|
||||
clickhouse:
|
||||
image: clickhouse/clickhouse-server:24-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
CLICKHOUSE_DB: ${CLICKHOUSE_DB}
|
||||
CLICKHOUSE_USER: ${CLICKHOUSE_USER}
|
||||
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD}
|
||||
CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: "1"
|
||||
ulimits:
|
||||
nofile: { soft: 262144, hard: 262144 }
|
||||
volumes:
|
||||
- ch_data:/var/lib/clickhouse
|
||||
- ch_logs:/var/log/clickhouse-server
|
||||
networks: [observability]
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8123/ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 6
|
||||
logging: &logging
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.110.0
|
||||
restart: unless-stopped
|
||||
command: ["--config=/etc/otelcol-contrib/config.yaml"]
|
||||
environment:
|
||||
CLICKHOUSE_DB: ${CLICKHOUSE_DB}
|
||||
CLICKHOUSE_USER: ${CLICKHOUSE_USER}
|
||||
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD}
|
||||
volumes:
|
||||
- ./observability/otel-collector-config.yaml:/etc/otelcol-contrib/config.yaml:ro
|
||||
expose: ["4317", "4318"] # OTLP gRPC / HTTP — reachable by backend on `internal`
|
||||
networks: [internal, observability]
|
||||
depends_on:
|
||||
clickhouse: { condition: service_healthy }
|
||||
logging: *logging
|
||||
|
||||
hdx-mongo:
|
||||
image: mongo:6
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- hdx_mongo:/data/db
|
||||
networks: [observability]
|
||||
logging: *logging
|
||||
|
||||
hyperdx:
|
||||
image: hyperdx/hyperdx:2
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MONGO_URI: mongodb://hdx-mongo:27017/hyperdx
|
||||
FRONTEND_URL: http://localhost:8080
|
||||
# Optional convenience: pre-seed the ClickHouse source so you skip the
|
||||
# first-run wizard (env names can vary by HyperDX version — see README).
|
||||
DEFAULT_CONNECTIONS: >
|
||||
[{"name":"ClickHouse","host":"http://clickhouse:8123",
|
||||
"username":"${CLICKHOUSE_USER}","password":"${CLICKHOUSE_PASSWORD}"}]
|
||||
ports: ["8080:8080"]
|
||||
networks: [observability]
|
||||
depends_on:
|
||||
hdx-mongo: { condition: service_started }
|
||||
clickhouse: { condition: service_healthy }
|
||||
logging: *logging
|
||||
@@ -0,0 +1,86 @@
|
||||
# Counsel Scorecard — application stack (backend + Postgres + migrate + Caddy).
|
||||
#
|
||||
# cp .env.example .env # then edit the change_me_* values
|
||||
# docker compose up -d --build
|
||||
#
|
||||
# Add the observability stack (OTel Collector + HyperDX + ClickHouse) with:
|
||||
# docker compose -f docker-compose.yml -f docker-compose.observability.yml up -d --build
|
||||
# and set OTEL_ENABLED=true in .env.
|
||||
|
||||
networks:
|
||||
edge:
|
||||
internal:
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
caddy_data:
|
||||
caddy_config:
|
||||
uploads:
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
expose: ["5432"] # never `ports` — DB is private to the docker network
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB}
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: ${DB_SUPERUSER_PASSWORD}
|
||||
DB_APP_PASSWORD: ${DB_APP_PASSWORD}
|
||||
DB_MIGRATOR_PASSWORD: ${DB_MIGRATOR_PASSWORD}
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./db/init:/docker-entrypoint-initdb.d:ro
|
||||
networks: [internal]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d ${POSTGRES_DB}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
logging: &logging
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# One-shot: applies migrations as `migrator` (DDL), then idempotent seed. Exits 0.
|
||||
migrate:
|
||||
build: ./backend
|
||||
restart: "no"
|
||||
env_file: .env
|
||||
command: ["sh", "-c", "alembic upgrade head && python -m app.seed"]
|
||||
networks: [internal]
|
||||
depends_on:
|
||||
postgres: { condition: service_healthy }
|
||||
logging: *logging
|
||||
|
||||
backend:
|
||||
build: ./backend
|
||||
restart: unless-stopped
|
||||
expose: ["8000"]
|
||||
env_file: .env
|
||||
command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
volumes:
|
||||
- uploads:/data/uploads
|
||||
networks: [edge, internal]
|
||||
depends_on:
|
||||
postgres: { condition: service_healthy }
|
||||
migrate: { condition: service_completed_successfully }
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/api/v1/health').status==200 else 1)"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 20s
|
||||
logging: *logging
|
||||
|
||||
caddy:
|
||||
image: caddy:2-alpine
|
||||
restart: unless-stopped
|
||||
ports: ["80:80", "443:443", "443:443/udp"]
|
||||
volumes:
|
||||
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
||||
- caddy_data:/data
|
||||
- caddy_config:/config
|
||||
networks: [edge]
|
||||
depends_on:
|
||||
backend: { condition: service_healthy }
|
||||
logging: *logging
|
||||
@@ -0,0 +1,57 @@
|
||||
# OpenTelemetry Collector (contrib) — receives OTLP from the FastAPI backend
|
||||
# and writes traces / metrics / logs into ClickHouse, which HyperDX queries.
|
||||
# This is the gate-clean "S3" pipeline from the spec: OTel Collector → ClickHouse → HyperDX.
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
processors:
|
||||
batch:
|
||||
timeout: 5s
|
||||
send_batch_size: 1024
|
||||
memory_limiter:
|
||||
check_interval: 2s
|
||||
limit_percentage: 80
|
||||
spike_limit_percentage: 25
|
||||
|
||||
exporters:
|
||||
clickhouse:
|
||||
endpoint: tcp://clickhouse:9000?dial_timeout=10s&compress=lz4
|
||||
database: ${env:CLICKHOUSE_DB}
|
||||
username: ${env:CLICKHOUSE_USER}
|
||||
password: ${env:CLICKHOUSE_PASSWORD}
|
||||
create_schema: true
|
||||
ttl: 720h # 30-day retention; tune per client storage budget
|
||||
logs_table_name: otel_logs
|
||||
traces_table_name: otel_traces
|
||||
metrics_table_name: otel_metrics
|
||||
timeout: 10s
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 5s
|
||||
max_interval: 30s
|
||||
debug:
|
||||
verbosity: basic
|
||||
|
||||
service:
|
||||
telemetry:
|
||||
logs:
|
||||
level: info
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [clickhouse, debug]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [clickhouse]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [clickhouse]
|
||||
Reference in New Issue
Block a user