Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
962dde69a4 | ||
|
|
a70b9282ef | ||
|
|
d379ce2288 | ||
|
|
82df340216 | ||
|
|
a1a7d5c196 | ||
|
|
6f5a004cbe | ||
|
|
008b35b9c3 | ||
|
|
040d41f76e | ||
|
|
f3ee57dff1 | ||
|
|
5e53ac11f1 | ||
|
|
d3cf08d47f | ||
|
|
598ba8782f | ||
|
|
e2c821e53d | ||
|
|
d429f4e292 | ||
|
|
1decacd9eb | ||
|
|
6dd749790e | ||
|
|
a27701ac85 | ||
|
|
add9767492 | ||
|
|
656da736ef | ||
|
|
4adfacaa7e |
@@ -161,3 +161,7 @@ FORWARDED_ALLOW_IPS=127.0.0.1
|
||||
OTEL_ENABLED=false
|
||||
OTEL_SERVICE_NAME=workflow-backend
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
|
||||
# The Archive's technical account (Atrium#53): the fixed id the hub creates it under. Here it may
|
||||
# reach only the evidence routes (GET /evidence); everywhere else it is a 404. Keep the default.
|
||||
ARCHIVE_READER_ID=a2c41e00-0000-4000-8000-000000000053
|
||||
|
||||
+23
-24
@@ -1,5 +1,20 @@
|
||||
name: CI
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
# main only: a branch is tested through its pull request (a push of many branches at once
|
||||
# must not flood the runners)
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch: # manual run: Actions -> CI -> Run workflow
|
||||
|
||||
# dredd-core is private on the Haski Gitea, and so is every repository this workflow may fetch.
|
||||
# All git traffic to the Gitea host (pip installing dredd-core from requirements, above all) goes
|
||||
# through the read-only bot haski-reader: its token is the Haski org secret DREDD_CORE_TOKEN,
|
||||
# which Gitea masks in logs. Docker builds get the same token as a BuildKit secret instead.
|
||||
env:
|
||||
GIT_CONFIG_COUNT: "1"
|
||||
GIT_CONFIG_KEY_0: url.http://x-access-token:${{ secrets.DREDD_CORE_TOKEN }}@77.216.148.202:3000/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: http://77.216.148.202:3000/
|
||||
|
||||
jobs:
|
||||
backend:
|
||||
@@ -45,17 +60,6 @@ jobs:
|
||||
-- EXISTS then no-ops, so the least-privilege migrator never needs extension rights.
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
SQL
|
||||
- name: Authenticate to dredd-core
|
||||
# dredd-core is a PRIVATE repo, so the `git+https://` requirement cannot be fetched
|
||||
# anonymously — without this step `pip install` fails with a git auth prompt/404.
|
||||
# The rewrite injects the token for that ONE repo URL; every other GitHub URL is untouched,
|
||||
# and the secret stays out of the requirements file and the pip log.
|
||||
# Add the secret under Settings → Secrets and variables → Actions → DREDD_CORE_TOKEN
|
||||
# (a fine-grained PAT with read-only Contents access on Alpaq92/dredd-core).
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
@@ -124,11 +128,6 @@ jobs:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with: { python-version: "3.12" }
|
||||
- name: Authenticate to dredd-core
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
@@ -265,7 +264,7 @@ jobs:
|
||||
# the whole ordering.
|
||||
run: |
|
||||
for i in $(seq 1 60); do
|
||||
if curl -fsS http://localhost/healthz >/dev/null 2>&1; then
|
||||
if curl -fsS http://localhost:8141/healthz >/dev/null 2>&1; then
|
||||
echo "ready after ~$((i * 5))s"; exit 0
|
||||
fi
|
||||
sleep 5
|
||||
@@ -277,17 +276,17 @@ jobs:
|
||||
- name: Drive it through the published backend
|
||||
run: |
|
||||
set -euo pipefail
|
||||
curl -fsS http://localhost/healthz
|
||||
headers=$(curl -fsSI http://localhost/)
|
||||
curl -fsS http://localhost:8141/healthz
|
||||
headers=$(curl -fsSI http://localhost:8141/)
|
||||
echo "$headers" | grep -qi "content-security-policy" || { echo "::error::no CSP on the console"; exit 1; }
|
||||
echo "$headers" | grep -qi "x-frame-options" || { echo "::error::no frame policy on the console"; exit 1; }
|
||||
curl -fsS http://localhost/ | grep -q "<title>Workflow" || { echo "::error::console did not render"; exit 1; }
|
||||
token=$(curl -fsS -X POST http://localhost/api/v1/auth/login \
|
||||
curl -fsS http://localhost:8141/ | grep -q "<title>Workflow" || { echo "::error::console did not render"; exit 1; }
|
||||
token=$(curl -fsS -X POST http://localhost:8141/api/v1/auth/login \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"email":"admin@example.com","password":"ci-admin-password-1"}' | jq -r .token)
|
||||
[ -n "$token" ] && [ "$token" != "null" ] || { echo "::error::login returned no token"; exit 1; }
|
||||
curl -fsS -H "Authorization: Bearer $token" http://localhost/api/v1/auth/me >/dev/null
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost/api/v1/auth/me)
|
||||
curl -fsS -H "Authorization: Bearer $token" http://localhost:8141/api/v1/auth/me >/dev/null
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost:8141/api/v1/auth/me)
|
||||
[ "$code" = "401" ] || { echo "::error::expected 401 without a session, got $code"; exit 1; }
|
||||
|
||||
- name: The least-privilege roles hold inside the container
|
||||
|
||||
@@ -89,6 +89,8 @@ backend/app/
|
||||
galena (ModuleClient wrapper; tests/fake_galena) · subjects (upload / pin / read)
|
||||
requests (types + requests + snapshot) · groups · templates · assignees
|
||||
runs (start, act) · notify · lists (inbox / mine / archive + CSV, can_* flags)
|
||||
legacy_import (Galena's old runs + templates as history; `python -m
|
||||
app.import_galena_runs runs.json [--commit]`, idempotent)
|
||||
routers/ health auth users admin dashboard (+ GET /stats)
|
||||
runs (runs, actions, stages, scan, /files upload, /options, inbox/mine/archive, notifications)
|
||||
templates · requests (fields, types, requests, GET /files/{id}) · groups
|
||||
@@ -333,9 +335,13 @@ the implementation plan's Part B and the module spec (paths in `.meduza/SPEC-wor
|
||||
settings (`DEFAULT_SETTINGS` + `merge_settings`, stable stage keys, notes ≤ 2000, required on
|
||||
reject / back / cancel / add_stage) and `services/engine.py` decides every action (`act()`:
|
||||
approve, reject, back, cancel, add_stage, refresh, paper_scan, edit_request) on a `RunState`.
|
||||
Refusal order is fixed: 404 -> 409 (stale `stage_key_seen` / `stages_seen`, not running) -> 403 ->
|
||||
422. Rejection follows §5.2a (back to the first or previous stage, a new round), not Galena's
|
||||
„rejection ends the run”. Keep new rules in these two files and test them DB-free.
|
||||
Refusal order is fixed: 404 -> 409 (stale `stage_key_seen` / `round_seen` / `stages_seen`, not
|
||||
running) -> 403 -> 422. Rejection follows §5.2a (back to the first or previous stage, a new round),
|
||||
not Galena's „rejection ends the run”. Keep new rules in these two files and test them DB-free.
|
||||
**The initiator lock is the moderator's**: `initiator_may_approve` is off by default, only a
|
||||
template can switch it on, and a run's `settings_override` may never lift it
|
||||
(`merge_settings(..., for_run=True)`, 422 `initiator_lock_fixed`) - otherwise anybody could lay out
|
||||
stages naming only themselves and emit `workflow.approved`, which Galena moves a card on.
|
||||
- **Who.** Read access is `services/authz.can_read_run` (a Galena document: Galena's `my_roles`
|
||||
alone; file / request: initiator, this module's moderators, the stage's people). Owner = initiator
|
||||
or Galena `manager` / moderator. Approvers are fixed on entering a stage (`run_stage_state`,
|
||||
|
||||
@@ -43,9 +43,14 @@ as a new round (§5.2a „Ustawienia obiegu”) instead of ending it.
|
||||
| `GET/POST/PATCH /admin/groups` | approver groups |
|
||||
| `GET /stats` | dredd-core `stats_contract` tiles |
|
||||
|
||||
Every action carries the stage and stage list it was decided on (`stage_key_seen` /
|
||||
`stages_seen`): a click on a run somebody else moved meanwhile is a 409, never a decision on a run
|
||||
nobody saw.
|
||||
Every action carries the stage, the round and the stage list it was decided on (`stage_key_seen` /
|
||||
`round_seen` / `stages_seen`): a click on a run somebody else moved meanwhile is a 409, never a
|
||||
decision on a run nobody saw - also when the run came back to the same stage in a new round. The
|
||||
console always sends all three; an API client that leaves out `round_seen` is not checked on it.
|
||||
|
||||
The initiator may not approve their own run unless a template allows it (`initiator_may_approve`,
|
||||
off by default). Only a moderator makes templates; the person starting a run may keep that lock or
|
||||
switch it on, never lift it (422 `initiator_lock_fixed`).
|
||||
|
||||
Standalone, the stack is published on port **8141**.
|
||||
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ── build stage: resolve dependencies, including the private one ─────────────
|
||||
# `dredd-core` is a private GitHub repository pinned by tag in requirements.txt, so installing it
|
||||
# `dredd-core` is a private repository on the Haski Gitea pinned by tag in requirements.txt, so installing it
|
||||
# needs two things the runtime image should never have: `git`, and a credential.
|
||||
#
|
||||
# The credential arrives as a BuildKit SECRET, not a build argument. A build arg is baked into the
|
||||
@@ -27,8 +27,8 @@ RUN --mount=type=secret,id=dredd_core_token,required=true \
|
||||
test -s /run/secrets/dredd_core_token \
|
||||
|| { echo "build secret dredd_core_token is empty - export DREDD_CORE_TOKEN" >&2; exit 1; }; \
|
||||
GIT_CONFIG_COUNT=1 \
|
||||
GIT_CONFIG_KEY_0="url.https://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@github.com/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="https://github.com/" \
|
||||
GIT_CONFIG_KEY_0="url.http://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@77.216.148.202:3000/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="http://77.216.148.202:3000/" \
|
||||
pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||
|
||||
# ── runtime stage: no git, no credential, no compiler ────────────────────────
|
||||
|
||||
@@ -12,6 +12,7 @@ no-op instead of a crash.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
@@ -144,6 +145,10 @@ class Settings(BaseSettings):
|
||||
# underscores no. A two-word app therefore has a schema `my_app` and a module slug `my-app`, and
|
||||
# the scaffolder derives the second from the first so the default is already legal.
|
||||
module_slug: str = "workflow"
|
||||
# The Archive's technical account (Atrium#53): the hub creates it under this fixed id, with no
|
||||
# password, and Galena carries its read-only token. Here it reaches `GET /evidence` and nothing
|
||||
# else (deps.get_current_user). An id, not an e-mail: nobody can register their way into it.
|
||||
archive_reader_id: uuid.UUID = uuid.UUID("a2c41e00-0000-4000-8000-000000000053")
|
||||
# Where people sign in when identity is shared — the hub's address as a BROWSER sees it, e.g.
|
||||
# /atrium/ on the platform. Empty standalone (there is no hub), and empty is survivable on the
|
||||
# platform too: the console then says where accounts live without linking to them. It is
|
||||
|
||||
@@ -29,6 +29,7 @@ from .enums import TokenScope
|
||||
from .errors import AuthenticationError, AuthorizationError
|
||||
from .models import AppUser
|
||||
from .services import auth as auth_service
|
||||
from .services import authz as authz_service
|
||||
from .services import moderation as moderation_service
|
||||
|
||||
SESSION_COOKIE = get_settings().session_cookie_name
|
||||
@@ -148,6 +149,10 @@ def get_current_user(request: Request, db: Session = Depends(get_db)) -> AppUser
|
||||
# at the edge of both shapes with no second code path — so never make it depend on
|
||||
# `shares_identity`.
|
||||
moderation_service.assert_may_use(db, user)
|
||||
# The Archive's technical account (Atrium#53) holds a platform credential, so without this it
|
||||
# would reach every screen here. It reaches the evidence routes and is refused (404) elsewhere.
|
||||
authz_service.assert_archive_reader_route(
|
||||
user, getattr(request.scope.get("route"), "path", request.url.path))
|
||||
|
||||
request.state.credential_id = credential.id
|
||||
request.state.credential_kind = credential.kind
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""One-shot import of Galena's own approval runs and templates.
|
||||
|
||||
python -m app.import_galena_runs runs.json # dry run: what would be imported
|
||||
python -m app.import_galena_runs runs.json --commit # import (one transaction)
|
||||
|
||||
`runs.json` is Galena's `python -m app.export_workflows --out runs.json`. Idempotent: ids derive from
|
||||
Galena's, so running it again — or on a later export — adds only what is missing. No `workflow.*`
|
||||
event, no notification. Rows that cannot be imported are listed as skipped; the rest goes in.
|
||||
Exit status 0 = done, 1 = refused (nothing written), 2 = usage.
|
||||
`services/legacy_import.py` says how each row is mapped.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
|
||||
from dredd_core.db import make_engine, make_session_factory
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from .config import get_settings
|
||||
from .errors import AppError
|
||||
from .services import legacy_import
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="python -m app.import_galena_runs",
|
||||
description="Import Galena's approval runs and templates as read-only history.")
|
||||
parser.add_argument("file", help="Galena's export (python -m app.export_workflows --out ...)")
|
||||
parser.add_argument("--commit", action="store_true", help="write it; without this, a dry run")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
with open(args.file, encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f"cannot read {args.file}: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
engine = make_engine(get_settings().database_url, poolclass=NullPool)
|
||||
try:
|
||||
with make_session_factory(engine)() as db:
|
||||
try:
|
||||
report = legacy_import.import_export(db, data)
|
||||
except AppError as exc:
|
||||
db.rollback()
|
||||
print(f"import refused, nothing written: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
except SQLAlchemyError as exc:
|
||||
db.rollback()
|
||||
print(f"import failed in the database, nothing written: {exc.__class__.__name__}: "
|
||||
f"{exc}", file=sys.stderr)
|
||||
return 1
|
||||
if args.commit:
|
||||
db.commit()
|
||||
else:
|
||||
db.rollback()
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
verb = "imported" if args.commit else "would import"
|
||||
print(f"{verb}: {report.templates} templates, {report.runs} runs "
|
||||
f"({report.already} already here)")
|
||||
for line in report.skipped:
|
||||
print(f"skipped {line}")
|
||||
if not args.commit:
|
||||
print("dry run: add --commit to write it")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
raise SystemExit(main())
|
||||
+3
-1
@@ -22,7 +22,8 @@ from .errors import ProblemDetailErrorMiddleware, install_error_handlers
|
||||
from .logging_config import configure_logging
|
||||
from .models import SHARED_TABLES
|
||||
from .observability import setup_observability
|
||||
from .routers import admin, auth, dashboard, groups, health, requests, runs, templates, users
|
||||
from .routers import (admin, auth, dashboard, evidence, groups, health, requests, runs, templates,
|
||||
users)
|
||||
|
||||
API_PREFIX = "/api/v1"
|
||||
|
||||
@@ -119,6 +120,7 @@ if settings.cors_origins_list:
|
||||
for router in (
|
||||
health.router, auth.router, users.router, admin.router,
|
||||
dashboard.router, runs.router, templates.router, requests.router, groups.router,
|
||||
evidence.router,
|
||||
):
|
||||
app.include_router(router, prefix=API_PREFIX)
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""The Archive's evidence contract (Atrium#53): what Galena copies into a contract's package.
|
||||
|
||||
`GET /evidence?document_id=` lists the finished runs on a Galena document; each item's `download`
|
||||
is a path under /api/v1/, same auth, always an attachment. The Archive's technical account may reach
|
||||
these routes and nothing else here (`deps.get_current_user`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from dredd_core.plain_files import response_headers
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import extract_token, get_current_user
|
||||
from ..models import AppUser
|
||||
from ..services import evidence
|
||||
|
||||
router = APIRouter(tags=["evidence"])
|
||||
|
||||
|
||||
def _token(request: Request) -> str:
|
||||
return extract_token(request) or ""
|
||||
|
||||
|
||||
def _attachment(db: Session, data: bytes, name: str) -> Response:
|
||||
db.commit() # the audit row of a technical-account read
|
||||
media, headers = response_headers(name, download=True)
|
||||
return Response(data, media_type=media, headers=headers)
|
||||
|
||||
|
||||
@router.get("/evidence")
|
||||
def list_evidence(document_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = evidence.for_document(db, user, document_id, token=_token(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/evidence/runs/{run_id}/timeline")
|
||||
def timeline(run_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
return _attachment(db, *evidence.timeline(db, user, run_id, token=_token(request)))
|
||||
|
||||
|
||||
@router.get("/evidence/runs/{run_id}/scan")
|
||||
def scan(run_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
return _attachment(db, *evidence.scan(db, user, run_id, token=_token(request)))
|
||||
@@ -154,7 +154,8 @@ def edit(request_id: uuid.UUID, request: Request, data: str = Form(...),
|
||||
body = _part(RequestPatch, data)
|
||||
edited = requests.update(db, user, request_id, title=body.title, values=body.values,
|
||||
files=files or [], note=body.note, stage_key_seen=body.stage_key_seen,
|
||||
stages_seen=body.stages_seen, token=_token(request),
|
||||
stages_seen=body.stages_seen, round_seen=body.round_seen,
|
||||
token=_token(request),
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return edited
|
||||
|
||||
@@ -103,8 +103,8 @@ def detail(run_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
def act(run_id: uuid.UUID, body: RunActionIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
run = runs.act(db, user, run_id, action=body.action, stage_key_seen=body.stage_key_seen,
|
||||
stages_seen=body.stages_seen, note=body.note, content_seen=body.content_seen,
|
||||
token=_token(request), ip=client_ip(request))
|
||||
stages_seen=body.stages_seen, round_seen=body.round_seen, note=body.note,
|
||||
content_seen=body.content_seen, token=_token(request), ip=client_ip(request))
|
||||
db.commit()
|
||||
return _done(run)
|
||||
|
||||
@@ -113,7 +113,7 @@ def act(run_id: uuid.UUID, body: RunActionIn, request: Request, db: Session = De
|
||||
def add_stage(run_id: uuid.UUID, body: AddStageIn, request: Request,
|
||||
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
run = runs.act(db, user, run_id, action="add_stage", stage_key_seen=body.stage_key_seen,
|
||||
stages_seen=body.stages_seen, note=body.note,
|
||||
stages_seen=body.stages_seen, round_seen=body.round_seen, note=body.note,
|
||||
new_stage=body.stage.model_dump(mode="json", exclude_none=True),
|
||||
token=_token(request), ip=client_ip(request))
|
||||
db.commit()
|
||||
@@ -123,12 +123,13 @@ def add_stage(run_id: uuid.UUID, body: AddStageIn, request: Request,
|
||||
@router.post("/runs/{run_id}/scan")
|
||||
def paper_scan(run_id: uuid.UUID, request: Request, file: UploadFile = File(...),
|
||||
stage_key_seen: str = Form(...), stages_seen: list[str] | None = Form(None),
|
||||
note: str | None = Form(None), db: Session = Depends(get_db),
|
||||
round_seen: int | None = Form(None), note: str | None = Form(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
"""The paper ending approved with the signed scan (multipart: `file` + the form fields)."""
|
||||
run = runs.act(db, user, run_id, action="paper_scan", stage_key_seen=stage_key_seen,
|
||||
stages_seen=stages_seen, note=note, scan=file, token=_token(request),
|
||||
ip=client_ip(request))
|
||||
stages_seen=stages_seen, round_seen=round_seen, note=note, scan=file,
|
||||
token=_token(request), ip=client_ip(request))
|
||||
db.commit()
|
||||
return _done(run)
|
||||
|
||||
|
||||
@@ -288,12 +288,13 @@ class RequestIn(In):
|
||||
|
||||
class RequestPatch(In):
|
||||
"""The JSON part of the multipart `PATCH /requests/{id}`. `values` is a partial write (a null
|
||||
value clears that field); `note` and the `*_seen` pair are the run's when one is in progress."""
|
||||
value clears that field); `note` and the `*_seen` fields are the run's when one is in progress."""
|
||||
title: str | None = None
|
||||
values: dict[str, Any] | None = None
|
||||
note: str | None = None
|
||||
stage_key_seen: str | None = None
|
||||
stages_seen: list[str] | None = None
|
||||
round_seen: int | None = None
|
||||
|
||||
|
||||
class RequestOut(BaseModel):
|
||||
@@ -351,6 +352,7 @@ class _Seen(In):
|
||||
"""What the caller saw: a click prepared before somebody else moved the run gets a 409."""
|
||||
stage_key_seen: str | None = None
|
||||
stages_seen: list[str] | None = None
|
||||
round_seen: int | None = None # the run's round; a new round is a new decision
|
||||
note: str | None = None
|
||||
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ from dredd_core.enums import NodeRole
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..config import get_settings
|
||||
from ..errors import NotFoundError
|
||||
from ..models import AppUser
|
||||
from ..models.workflow import RunStageState, WorkflowRun
|
||||
@@ -128,3 +129,19 @@ def is_owner(db: DbSession, user: AppUser, run: WorkflowRun, *, token: str) -> b
|
||||
if run.ref_document_id is not None:
|
||||
return _galena_role(run, token=token) == NodeRole.manager
|
||||
return moderation.is_moderator(db, user)
|
||||
|
||||
|
||||
# ── the Archive's technical account (Atrium#53) ───────────────────────────────
|
||||
#: The only routes it may reach: the evidence a Galena archive package is collected from.
|
||||
EVIDENCE_PREFIX = "/api/v1/evidence"
|
||||
|
||||
|
||||
def is_archive_reader(user: AppUser) -> bool:
|
||||
"""The hub's passwordless account Galena collects evidence with (fixed id, read-only token)."""
|
||||
return user.id == get_settings().archive_reader_id
|
||||
|
||||
|
||||
def assert_archive_reader_route(user: AppUser, route_path: str) -> None:
|
||||
"""The technical account reads evidence and nothing else: 404 anywhere else, as for a stranger."""
|
||||
if is_archive_reader(user) and not route_path.startswith(EVIDENCE_PREFIX):
|
||||
raise NotFoundError("Not found.")
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""What Galena's Archive collects from this module for one document (Atrium#53, contract `evidence`).
|
||||
|
||||
`GET /evidence?document_id=` lists, for every finished run on that Galena document, its timeline as
|
||||
JSON (who / what / when / notes, the template, the stages) and its paper scan when it has one. The
|
||||
timeline is rendered deterministically, so its sha256 is stable from one call to the next.
|
||||
|
||||
Two callers. A person sees the runs they may read (`authz.can_read_run`: Galena's roles on the
|
||||
document). The Archive's technical account sees every finished run on it, and each use is audited
|
||||
(`evidence.read`, flat identifiers only).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from dredd_core.document_ref import from_dict
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..config import get_settings
|
||||
from ..errors import NotFoundError
|
||||
from ..models import AppUser
|
||||
from ..models.workflow import RunStatus, WorkflowEvent, WorkflowRun
|
||||
from . import audit, authz, subjects
|
||||
|
||||
|
||||
def _audit(db: DbSession, user: AppUser, entity_type: str, entity_id: Any, detail: str) -> None:
|
||||
if authz.is_archive_reader(user):
|
||||
audit.record(db, actor_id=user.id, action="evidence.read", entity_type=entity_type,
|
||||
entity_id=entity_id, detail=detail)
|
||||
|
||||
|
||||
def _readable(db: DbSession, user: AppUser, run: WorkflowRun, *, token: str) -> bool:
|
||||
return authz.is_archive_reader(user) or authz.can_read_run(db, user, run, token=token)
|
||||
|
||||
|
||||
def _finished(db: DbSession, document_id: uuid.UUID) -> list[WorkflowRun]:
|
||||
return list(db.scalars(
|
||||
select(WorkflowRun)
|
||||
.where(WorkflowRun.ref_document_id == document_id,
|
||||
WorkflowRun.state != RunStatus.running.value)
|
||||
.order_by(WorkflowRun.created_at, WorkflowRun.id)))
|
||||
|
||||
|
||||
def _run(db: DbSession, user: AppUser, run_id: uuid.UUID, *, token: str) -> WorkflowRun:
|
||||
"""A finished run on a Galena document that `user` may read; 404 otherwise."""
|
||||
run = db.get(WorkflowRun, run_id)
|
||||
if (run is None or run.ref_document_id is None or run.state == RunStatus.running.value
|
||||
or not _readable(db, user, run, token=token)):
|
||||
raise NotFoundError("Not found.")
|
||||
return run
|
||||
|
||||
|
||||
def _scan_name(ref: Any) -> str:
|
||||
"""A FileRef keeps its name; a scan Galena published is named by its path."""
|
||||
return getattr(ref, "name", None) or getattr(ref, "path", "").rsplit("/", 1)[-1] or "skan.pdf"
|
||||
|
||||
|
||||
def _when(value: Any) -> str | None:
|
||||
return value.isoformat() if value is not None else None
|
||||
|
||||
|
||||
def timeline_doc(run: WorkflowRun, events: list[Any], people: dict[uuid.UUID, Any]) -> bytes:
|
||||
"""The run as the archive keeps it: canonical JSON (sorted keys, no spaces), so the same run
|
||||
always hashes the same."""
|
||||
def who(user_id: uuid.UUID) -> dict[str, Any]:
|
||||
person = people.get(user_id)
|
||||
return {"id": str(user_id), "name": getattr(person, "full_name", None),
|
||||
"email": getattr(person, "email", None)}
|
||||
|
||||
doc = {
|
||||
"run_id": str(run.id), "document_id": str(run.ref_document_id),
|
||||
"path": run.ref_path, "commit_sha": run.ref_commit_sha, "sha256": run.ref_sha256,
|
||||
"state": run.state, "round": run.round, "started_by": who(run.started_by),
|
||||
"template_id": str(run.template_id) if run.template_id else None,
|
||||
"template_name": run.template_name, "stages": run.stages, "settings": run.settings,
|
||||
"timeline": [{
|
||||
"kind": e.kind, "stage_from": e.stage_from, "stage_to": e.stage_to, "round": e.round,
|
||||
"actor": who(e.actor_id), "note": e.note, "evidence": e.evidence,
|
||||
"at": _when(e.created_at)} for e in events],
|
||||
"finished_at": _when(run.updated_at),
|
||||
}
|
||||
return json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
|
||||
default=str).encode("utf-8")
|
||||
|
||||
|
||||
def _timeline(db: DbSession, run: WorkflowRun) -> bytes:
|
||||
events = list(db.scalars(select(WorkflowEvent).where(WorkflowEvent.run_id == run.id)
|
||||
.order_by(WorkflowEvent.created_at, WorkflowEvent.id)))
|
||||
ids = {run.started_by, *(e.actor_id for e in events)}
|
||||
people = {u.id: u for u in db.scalars(select(AppUser).where(AppUser.id.in_(ids)))}
|
||||
return timeline_doc(run, events, people)
|
||||
|
||||
|
||||
def items_for(run: WorkflowRun, timeline: bytes) -> list[dict[str, Any]]:
|
||||
"""The run's entries in the evidence list: its timeline, then its paper scan if it has one."""
|
||||
out = [{"kind": "timeline", "name": f"obieg-{run.id}.json",
|
||||
"sha256": hashlib.sha256(timeline).hexdigest(), "source_id": str(run.id),
|
||||
"commit_sha": run.ref_commit_sha,
|
||||
"download": f"evidence/runs/{run.id}/timeline"}]
|
||||
if run.scan:
|
||||
scan = from_dict(run.scan)
|
||||
out.append({"kind": "paper_scan", "name": _scan_name(scan),
|
||||
"sha256": scan.sha256, "source_id": str(run.id),
|
||||
"commit_sha": getattr(scan, "commit_sha", None),
|
||||
"download": f"evidence/runs/{run.id}/scan"})
|
||||
return out
|
||||
|
||||
|
||||
def for_document(db: DbSession, user: AppUser, document_id: uuid.UUID, *,
|
||||
token: str) -> dict[str, Any]:
|
||||
"""The contract's answer: always 200, empty items and a note when nothing is there."""
|
||||
items: list[dict[str, Any]] = []
|
||||
for run in _finished(db, document_id):
|
||||
if _readable(db, user, run, token=token):
|
||||
items += items_for(run, _timeline(db, run))
|
||||
_audit(db, user, "document", document_id, f"{len(items)} items")
|
||||
return {"module": get_settings().module_slug, "document_id": str(document_id),
|
||||
"items": items,
|
||||
"note": None if items else "Brak zakończonych obiegów akceptacji tego dokumentu."}
|
||||
|
||||
|
||||
def timeline(db: DbSession, user: AppUser, run_id: uuid.UUID, *, token: str) -> tuple[bytes, str]:
|
||||
run = _run(db, user, run_id, token=token)
|
||||
_audit(db, user, "workflow_run", run.id, "timeline")
|
||||
return _timeline(db, run), f"obieg-{run.id}.json"
|
||||
|
||||
|
||||
def scan(db: DbSession, user: AppUser, run_id: uuid.UUID, *, token: str) -> tuple[bytes, str]:
|
||||
run = _run(db, user, run_id, token=token)
|
||||
if not run.scan:
|
||||
raise NotFoundError("Not found.")
|
||||
ref = from_dict(run.scan)
|
||||
_audit(db, user, "workflow_run", run.id, "paper_scan")
|
||||
return subjects.read(ref, token=token), _scan_name(ref)
|
||||
|
||||
|
||||
__all__ = ["for_document", "items_for", "scan", "timeline", "timeline_doc"]
|
||||
@@ -0,0 +1,263 @@
|
||||
"""Galena's own approval runs, imported as read-only history (Atrium#53: one approval engine).
|
||||
|
||||
Galena drains its old engine (`LEGACY_WORKFLOWS=drain`) and exports its templates and FINISHED runs
|
||||
(`python -m app.export_workflows` there, format `galena-workflows/1`). This reads that file.
|
||||
|
||||
* **Templates** become Workflow templates under the rules of THIS module: same stages and keys,
|
||||
quorum "one" (the old engine had no other), and DEFAULT_SETTINGS for rejection (§5.2a, back a
|
||||
stage or to the first), so a run started from them now follows it.
|
||||
An archived template stays archived. A template naming a person who no longer exists is skipped.
|
||||
* **Runs** keep what happened: their state, stages, timeline, times and people. Their settings say
|
||||
`end` for rejection, because under the old engine a rejection ended the run — the history must not
|
||||
claim a rule it did not run under. Each is on the `DocumentRef` the export pinned (the project's
|
||||
main file); a run the export could not pin (`subject: null`) is reported, never imported.
|
||||
* **A bad row is skipped and reported**, never fatal: one malformed run must not hold back the rest.
|
||||
* **Idempotent.** Every id is derived from the Galena id (uuid5), so a second import of the same file,
|
||||
or of a later export with more finished runs, adds only what is missing.
|
||||
* **History, not activity.** No `workflow.*` event (Galena already emitted them when it happened), no
|
||||
notification. One audit row per imported run and template, actor NULL: the installation did it.
|
||||
One transaction for the whole file — all or nothing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import datetime as dt
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from dredd_core import workflow_contract
|
||||
from dredd_core.document_ref import DocumentRef, to_dict
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..errors import AppError, ValidationError
|
||||
from ..models import AppUser
|
||||
from ..models.workflow import EventKind, RunStatus, WorkflowEvent, WorkflowRun, WorkflowTemplate
|
||||
from . import audit, rules
|
||||
|
||||
FORMAT = "galena-workflows/1"
|
||||
_NS = uuid.UUID("5f0c1a52-9d36-4f4e-9b0a-6a3f2e3d4c11") # fixed: ids must be the same on every run
|
||||
_HEX40, _HEX64 = re.compile(r"^[0-9a-f]{40}$"), re.compile(r"^[0-9a-f]{64}$")
|
||||
_FINISHED = {RunStatus.approved.value, RunStatus.rejected.value, RunStatus.cancelled.value}
|
||||
_KINDS = {"start": EventKind.start, "zatwierdzenie": EventKind.approval,
|
||||
"odrzucenie": EventKind.rejection, "anulowanie": EventKind.cancellation,
|
||||
"zakonczenie": EventKind.finished}
|
||||
_BAD_ROW = (AppError, KeyError, TypeError, ValueError, AttributeError)
|
||||
|
||||
|
||||
def state_of(state: str, scan: dict | None, stages: list[dict]) -> str:
|
||||
"""The old engine had no "signed": an approval that ended with the scan of a paper signature was
|
||||
`zatwierdzony`. Here that is `podpisany`, so the lists, the archive filter and the CSV say so."""
|
||||
if (state == RunStatus.approved.value and scan is not None and stages
|
||||
and stages[-1].get("type") == rules.PAPER):
|
||||
return RunStatus.signed.value
|
||||
return state
|
||||
|
||||
|
||||
def new_id(kind: str, galena_id: str) -> uuid.UUID:
|
||||
"""The id this module gives a Galena row: the same every time, distinct per kind."""
|
||||
return uuid.uuid5(_NS, f"galena:{kind}:{galena_id}")
|
||||
|
||||
|
||||
def _when(value: str | None) -> dt.datetime | None:
|
||||
return dt.datetime.fromisoformat(value) if value else None
|
||||
|
||||
|
||||
def stages_of(old: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Old stages in this module's shape: the same keys, names, types and approvers, quorum "one"."""
|
||||
sent = [{**{k: v for k, v in s.items() if k in ("key", "name", "type", "approver")},
|
||||
"quorum": "one"} for s in old]
|
||||
return rules.stages(sent, subject_kind=workflow_contract.DOCUMENT,
|
||||
known_keys=[s.get("key") for s in old if s.get("key")])
|
||||
|
||||
|
||||
def evidence_of(value: str | None) -> dict[str, str] | None:
|
||||
"""The old evidence string (a commit for a content review, a scan's sha256) as this module's."""
|
||||
if value and _HEX40.match(value):
|
||||
return {"commit_sha": value}
|
||||
if value and _HEX64.match(value):
|
||||
return {"sha256": value}
|
||||
return None
|
||||
|
||||
|
||||
def stage_to(kind: str, stage: int | None, count: int) -> int | None:
|
||||
"""Where the old event left the run: an approval moves on (or ends it), the rest end it."""
|
||||
if kind == "start":
|
||||
return 0
|
||||
if kind == "zatwierdzenie" and stage is not None and stage + 1 < count:
|
||||
return stage + 1
|
||||
return None
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class Report:
|
||||
templates: int = 0
|
||||
runs: int = 0
|
||||
already: int = 0
|
||||
skipped: list[str] = dataclasses.field(default_factory=list)
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class _Known:
|
||||
"""What already exists, read once for the whole file instead of once per row."""
|
||||
people: set[str]
|
||||
templates: set[uuid.UUID]
|
||||
runs: set[uuid.UUID]
|
||||
|
||||
|
||||
def _uuid_or_none(value: Any) -> uuid.UUID | None:
|
||||
try:
|
||||
return uuid.UUID(str(value))
|
||||
except (TypeError, ValueError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
def _why(exc: Exception) -> str:
|
||||
return str(exc) if isinstance(exc, AppError) else f"malformed ({type(exc).__name__}: {exc})"
|
||||
|
||||
|
||||
def _rows(data: dict[str, Any], key: str, report: Report) -> list[dict[str, Any]]:
|
||||
rows = data.get(key) or []
|
||||
if not isinstance(rows, list):
|
||||
raise ValidationError(f"Not a Galena export: `{key}` is not a list.")
|
||||
for i, x in enumerate(rows):
|
||||
if not isinstance(x, dict):
|
||||
report.skipped.append(f"{key}[{i}]: malformed (not an object)")
|
||||
return [x for x in rows if isinstance(x, dict)]
|
||||
|
||||
|
||||
def _named_in(stages: Any) -> list[Any]:
|
||||
out: list[Any] = []
|
||||
for s in stages if isinstance(stages, list) else []:
|
||||
a = s.get("approver") if isinstance(s, dict) else None
|
||||
if isinstance(a, dict) and a.get("kind") == "users" and isinstance(a.get("user_ids"), list):
|
||||
out.extend(a["user_ids"])
|
||||
return out
|
||||
|
||||
|
||||
def _known(db: DbSession, templates: list[dict], runs: list[dict]) -> _Known:
|
||||
ids: list[Any] = []
|
||||
for t in templates:
|
||||
ids.extend(_named_in(t.get("stages")))
|
||||
for r in runs:
|
||||
ids.append(r.get("started_by"))
|
||||
ids.extend(e.get("actor_id") for e in (r.get("events") or []) if isinstance(e, dict))
|
||||
people = {u for u in map(_uuid_or_none, ids) if u is not None}
|
||||
tids = [new_id("template", str(t.get("id"))) for t in templates]
|
||||
rids = [new_id("run", str(r.get("id"))) for r in runs]
|
||||
return _Known(
|
||||
people={str(i) for i in db.scalars(select(AppUser.id).where(AppUser.id.in_(people)))}
|
||||
if people else set(),
|
||||
templates=set(db.scalars(select(WorkflowTemplate.id).where(WorkflowTemplate.id.in_(tids))))
|
||||
if tids else set(),
|
||||
runs=set(db.scalars(select(WorkflowRun.id).where(WorkflowRun.id.in_(rids)))) if rids else set())
|
||||
|
||||
|
||||
def _missing(ids: Any, known: _Known) -> bool:
|
||||
"""True when any id is not a person who exists (an unparseable id raises ValueError)."""
|
||||
return any(str(uuid.UUID(str(i))) not in known.people for i in ids)
|
||||
|
||||
|
||||
def _template(db: DbSession, t: dict[str, Any], known: _Known, report: Report) -> None:
|
||||
label = f"template {t.get('id')} ({t.get('name')})"
|
||||
try:
|
||||
tid = new_id("template", t["id"])
|
||||
if tid in known.templates:
|
||||
report.already += 1
|
||||
return
|
||||
stages = stages_of(t["stages"])
|
||||
name = rules.name(t["name"], "A template's name")
|
||||
if _missing(_named_in(stages), known):
|
||||
report.skipped.append(f"{label}: names a person who no longer exists")
|
||||
return
|
||||
template = WorkflowTemplate(
|
||||
id=tid, name=name, stages=stages, archived=bool(t.get("archived")),
|
||||
settings=rules.merge_settings({"initiator_may_approve": bool(t["initiator_may_approve"])}),
|
||||
created_at=_when(t.get("created_at")))
|
||||
except _BAD_ROW as exc:
|
||||
report.skipped.append(f"{label}: {_why(exc)}")
|
||||
return
|
||||
db.add(template)
|
||||
known.templates.add(tid)
|
||||
audit.record(db, actor_id=None, action="workflow_template.import", entity_type="workflow_template",
|
||||
entity_id=tid, detail=f"galena {t['id']}")
|
||||
report.templates += 1
|
||||
|
||||
|
||||
def _run(db: DbSession, r: dict[str, Any], known: _Known, report: Report) -> None:
|
||||
label = f"run {r.get('id')} (document {r.get('node_id')})"
|
||||
try:
|
||||
rid = new_id("run", r["id"])
|
||||
if rid in known.runs:
|
||||
report.already += 1
|
||||
return
|
||||
if r.get("subject") is None:
|
||||
report.skipped.append(f"{label}: not pinned by the export ({r.get('skipped')})")
|
||||
return
|
||||
if r["state"] not in _FINISHED:
|
||||
report.skipped.append(f"{label}: state {r['state']!r} is not a finished one")
|
||||
return
|
||||
events = r.get("events") or []
|
||||
if _missing([r["started_by"], *(e["actor_id"] for e in events)], known):
|
||||
report.skipped.append(f"{label}: a person in its timeline no longer exists")
|
||||
return
|
||||
s = r["subject"]
|
||||
subject = DocumentRef(document_id=s["document_id"], path=s["path"],
|
||||
commit_sha=s["commit_sha"], sha256=s["sha256"])
|
||||
stages = stages_of(r["stages"])
|
||||
scan = None
|
||||
if r.get("scan") and r["scan"].get("commit_sha") and r["scan"].get("sha256"):
|
||||
# The shape `runs.act` writes (`to_dict`, its `kind` included), so `from_dict` reads it.
|
||||
scan = to_dict(DocumentRef(document_id=s["document_id"], path=r["scan"]["path"],
|
||||
commit_sha=r["scan"]["commit_sha"],
|
||||
sha256=r["scan"]["sha256"]))
|
||||
timeline = []
|
||||
for e in events:
|
||||
kind = _KINDS.get(e["kind"])
|
||||
if kind is None:
|
||||
raise ValidationError(f"unknown event kind {e['kind']!r}")
|
||||
timeline.append(WorkflowEvent(
|
||||
id=new_id("event", e["id"]), run_id=rid, kind=kind.value,
|
||||
stage_from=None if e["kind"] == "start" else e.get("stage"),
|
||||
stage_to=stage_to(e["kind"], e.get("stage"), len(stages)), round=1,
|
||||
actor_id=uuid.UUID(e["actor_id"]), note=e.get("note"),
|
||||
evidence=evidence_of(e.get("evidence")), created_at=_when(e["created_at"])))
|
||||
template_id = new_id("template", r["template_id"]) if r.get("template_id") else None
|
||||
run = WorkflowRun(
|
||||
id=rid, template_id=template_id if template_id in known.templates else None,
|
||||
template_name=r["template_name"], stages=stages,
|
||||
# Under the old engine a rejection ended the run: the history keeps that rule.
|
||||
settings=rules.merge_settings({
|
||||
"initiator_may_approve": bool(r["initiator_may_approve"]),
|
||||
"on_reject_by_owner": "end", "on_reject_by_approver": "end"}),
|
||||
current=None, state=state_of(r["state"], scan, stages),
|
||||
started_by=uuid.UUID(r["started_by"]), round=1, scan=scan,
|
||||
created_at=_when(r.get("created_at")), updated_at=_when(r.get("updated_at")))
|
||||
run.set_ref(subject)
|
||||
except _BAD_ROW as exc:
|
||||
report.skipped.append(f"{label}: {_why(exc)}")
|
||||
return
|
||||
db.add(run)
|
||||
db.flush() # the run before its timeline: no relationship() orders the INSERTs
|
||||
for event in timeline:
|
||||
db.add(event)
|
||||
known.runs.add(rid)
|
||||
audit.record(db, actor_id=None, action="workflow_run.import", entity_type="workflow_run",
|
||||
entity_id=rid, detail=f"galena {r['id']}, {r['state']}, {len(events)} events")
|
||||
report.runs += 1
|
||||
|
||||
|
||||
def import_export(db: DbSession, data: dict[str, Any]) -> Report:
|
||||
"""Import a Galena export into `db` (no commit: the caller commits once, all or nothing)."""
|
||||
if not isinstance(data, dict) or data.get("format") != FORMAT:
|
||||
raise ValidationError(f"Not a Galena export (expected format {FORMAT}).")
|
||||
report = Report()
|
||||
templates, runs = _rows(data, "templates", report), _rows(data, "runs", report)
|
||||
known = _known(db, templates, runs)
|
||||
for t in templates:
|
||||
_template(db, t, known, report)
|
||||
db.flush()
|
||||
for r in runs:
|
||||
_run(db, r, known, report)
|
||||
return report
|
||||
@@ -254,11 +254,11 @@ def apply_edit(db: DbSession, actor: AppUser, request: WorkflowRequest, *, title
|
||||
|
||||
def update(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, title: Any = None,
|
||||
values: Mapping[str, Any] | None = None, files: Sequence[subjects.Upload] = (),
|
||||
note: Any = None, stage_key_seen: Any = None, stages_seen: Any = None, token: str,
|
||||
ip: str | None = None) -> WorkflowRequest:
|
||||
note: Any = None, stage_key_seen: Any = None, stages_seen: Any = None,
|
||||
round_seen: Any = None, token: str, ip: str | None = None) -> WorkflowRequest:
|
||||
"""Edit a request as its filer or a moderator (404 for anybody else). In a run: 409 when the
|
||||
request is locked, else the run's `edit_request` (`note`, `stage_key_seen`, `stages_seen` are
|
||||
the run's). No commit."""
|
||||
request is locked, else the run's `edit_request` (`note` and the `*_seen` fields are the
|
||||
run's). No commit."""
|
||||
from . import runs # runs imports this module
|
||||
|
||||
request = db.get(WorkflowRequest, request_id)
|
||||
@@ -279,7 +279,7 @@ def update(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, title: Any =
|
||||
raise ConflictError("This request is locked while its workflow is in progress.",
|
||||
{"code": "request_locked"})
|
||||
runs.act(db, actor, run_id, action="edit_request", note=note, stage_key_seen=stage_key_seen,
|
||||
stages_seen=stages_seen, edit=edit, token=token, ip=ip)
|
||||
stages_seen=stages_seen, round_seen=round_seen, edit=edit, token=token, ip=ip)
|
||||
return request
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,12 @@ the caller's job.
|
||||
was sent and lays it over a base (the defaults, or a template's settings for a run's override), so
|
||||
a template that never touched them runs on `DEFAULT_SETTINGS`.
|
||||
|
||||
**The initiator lock is the moderator's.** By default the initiator may not approve their own run
|
||||
(`initiator_may_approve` False), so nobody ends a run approved alone. Only a template - which only a
|
||||
moderator makes - can allow it; the person starting a run may keep the lock or switch it on, never
|
||||
off (`merge_settings(..., for_run=True)`: 422 `initiator_lock_fixed`). Otherwise anybody could lay
|
||||
out their own stages naming themselves and emit `workflow.approved`, which other modules act on.
|
||||
|
||||
**Stages.** 1 to `MAX_STAGES`, each with a name (1-60 after strip), a type, who approves it and
|
||||
how many of them must (`quorum`). A role approves a stage only on a Galena document: Workflow knows
|
||||
no tree for a file or a request. The paper ending is one stage, always the last. A stage keeps the
|
||||
@@ -47,7 +53,7 @@ DEFAULT_SETTINGS: dict[str, Any] = {
|
||||
"on_reject_by_approver": "previous",
|
||||
"notify_on_reject": ["owner"],
|
||||
"resolve": "on_enter",
|
||||
"initiator_may_approve": True,
|
||||
"initiator_may_approve": False,
|
||||
}
|
||||
|
||||
_POLISH = str.maketrans("ąćęłńóśźżĄĆĘŁŃÓŚŹŻ", "acelnoszzACELNOSZZ")
|
||||
@@ -144,8 +150,12 @@ _SETTING_CHECKS = {
|
||||
}
|
||||
|
||||
|
||||
def merge_settings(sent: Any, base: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""`sent` validated and laid over `base` (DEFAULT_SETTINGS when None). None sent = `base`."""
|
||||
def merge_settings(sent: Any, base: dict[str, Any] | None = None, *,
|
||||
for_run: bool = False) -> dict[str, Any]:
|
||||
"""`sent` validated and laid over `base` (DEFAULT_SETTINGS when None). None sent = `base`.
|
||||
|
||||
`for_run`: `sent` is the override of the person starting a run, who may not lift the initiator
|
||||
lock `base` keeps (422 `initiator_lock_fixed`); a template's own settings are a moderator's."""
|
||||
out = {k: (list(v) if isinstance(v, list) else v)
|
||||
for k, v in (DEFAULT_SETTINGS if base is None else base).items()}
|
||||
if sent is None:
|
||||
@@ -155,8 +165,12 @@ def merge_settings(sent: Any, base: dict[str, Any] | None = None) -> dict[str, A
|
||||
unknown = sorted(str(k) for k in sent if k not in _SETTING_CHECKS)
|
||||
if unknown:
|
||||
raise _bad("settings_unknown_key", f"Unknown setting: {', '.join(unknown)}.")
|
||||
allowed = out.get("initiator_may_approve", False)
|
||||
for key, value in sent.items():
|
||||
out[key] = _SETTING_CHECKS[key](value)
|
||||
if for_run and out.get("initiator_may_approve") and not allowed:
|
||||
raise _bad("initiator_lock_fixed",
|
||||
"Only a template can let the initiator approve their own workflow.")
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -195,10 +195,11 @@ def _layout(db: DbSession, kind: str, template_id: uuid.UUID | None, stages: Any
|
||||
template = None if template_id is None else _template(db, template_id)
|
||||
if template is None:
|
||||
laid_out = rules.stages(stages, subject_kind=kind)
|
||||
return None, laid_out, rules.merge_settings(settings_override)
|
||||
return None, laid_out, rules.merge_settings(settings_override, for_run=True)
|
||||
sent = [dict(s) for s in template.stages] if stages is None else stages
|
||||
laid_out = rules.stages(sent, subject_kind=kind, known_keys=[s["key"] for s in template.stages])
|
||||
return template, laid_out, rules.merge_settings(settings_override, template.settings)
|
||||
return template, laid_out, rules.merge_settings(settings_override, template.settings,
|
||||
for_run=True)
|
||||
|
||||
|
||||
def start(db: DbSession, actor: AppUser, *, subject: Subject, template_id: uuid.UUID | None = None,
|
||||
@@ -289,15 +290,21 @@ _TICK = dt.timedelta(microseconds=1)
|
||||
|
||||
|
||||
def assert_current(run: WorkflowRun, *, action: str, stage_key_seen: Any,
|
||||
stages_seen: Any) -> None:
|
||||
"""The 409s of an action: the run still in progress, on the stage and with the stages the
|
||||
caller saw. A click prepared before somebody else moved the run must not pass."""
|
||||
stages_seen: Any, round_seen: Any = None) -> None:
|
||||
"""The 409s of an action: the run still in progress, on the stage, in the round and with the
|
||||
stages the caller saw. A click prepared before somebody else moved the run must not pass - also
|
||||
when the run came back to the same stage in a new round (an edit of the request, a rejection on
|
||||
the first stage): the stage key is the same there, what is being approved is not."""
|
||||
if run.state != RunStatus.running.value or run.current is None:
|
||||
raise ConflictError("This workflow has already ended.", {"code": "not_running"})
|
||||
if (action in _ON_STAGE or stage_key_seen is not None) and \
|
||||
stage_key_seen != run.stages[run.current]["key"]:
|
||||
raise ConflictError("The workflow changed in the meantime. Refresh the view.",
|
||||
{"code": "stage_changed"})
|
||||
if round_seen is not None and (not isinstance(round_seen, int) or isinstance(round_seen, bool)
|
||||
or round_seen != run.round):
|
||||
raise ConflictError("The workflow changed in the meantime. Refresh the view.",
|
||||
{"code": "round_changed"})
|
||||
if stages_seen is not None and (not isinstance(stages_seen, list | tuple)
|
||||
or list(stages_seen) != [s["key"] for s in run.stages]):
|
||||
raise ConflictError("The workflow changed in the meantime. Refresh the view.",
|
||||
@@ -407,18 +414,20 @@ def _stage_row(db: DbSession, run_id: uuid.UUID, key: str,
|
||||
|
||||
|
||||
def act(db: DbSession, actor: AppUser, run_id: uuid.UUID, *, action: str,
|
||||
stage_key_seen: Any = None, stages_seen: Any = None, note: Any = None,
|
||||
new_stage: Any = None, content_seen: Any = None, scan: Any = None,
|
||||
stage_key_seen: Any = None, stages_seen: Any = None, round_seen: Any = None,
|
||||
note: Any = None, new_stage: Any = None, content_seen: Any = None, scan: Any = None,
|
||||
edit: dict[str, Any] | None = None, token: str, ip: str | None = None) -> WorkflowRun:
|
||||
"""Act on run `run_id` as `actor`: any of `ACTIONS`. `scan` is the paper ending's upload,
|
||||
`edit` the request changes `requests.update` hands over with `edit_request`. No commit."""
|
||||
`edit` the request changes `requests.update` hands over with `edit_request`. `round_seen` is
|
||||
checked when sent (the console always sends it). No commit."""
|
||||
if action not in ACTIONS:
|
||||
raise _bad("action_invalid", "Unknown workflow action.")
|
||||
if (action == "edit_request") != (edit is not None):
|
||||
raise _bad("edit_invalid", "A request is edited through the request.")
|
||||
run = _locked(db, run_id)
|
||||
authz.assert_can_read_run(db, actor, run, token=token)
|
||||
assert_current(run, action=action, stage_key_seen=stage_key_seen, stages_seen=stages_seen)
|
||||
assert_current(run, action=action, stage_key_seen=stage_key_seen, stages_seen=stages_seen,
|
||||
round_seen=round_seen)
|
||||
|
||||
rows = {r.stage_key: r for r in db.scalars(
|
||||
select(RunStageState).where(RunStageState.run_id == run.id))}
|
||||
|
||||
@@ -23,9 +23,9 @@
|
||||
# nothing else.
|
||||
#
|
||||
# The repo is PRIVATE, so pip needs credentials to fetch it:
|
||||
# local — a GitHub PAT in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the DREDD_CORE_TOKEN repo secret; see the auth step in .github/workflows/ci.yml
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.24.0
|
||||
# local — a read-only Gitea access token in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the Haski org secret DREDD_CORE_TOKEN; see the workflow-level `env:` in .github/workflows/
|
||||
dredd-core @ git+http://77.216.148.202:3000/Haski/dredd-core.git@v0.24.0
|
||||
|
||||
# Web framework
|
||||
fastapi==0.115.6
|
||||
@@ -41,6 +41,8 @@ pydantic-settings==2.7.1
|
||||
SQLAlchemy==2.0.50
|
||||
alembic==1.14.0
|
||||
pg8000==1.31.2 # pure-Python PostgreSQL driver, BSD-3-Clause (no LGPL, no libpq)
|
||||
scramp==1.4.6 # pg8000's SCRAM, MIT-0. Held below 1.5.0: with pg8000 1.31.2 it breaks a
|
||||
# TLS connection (make_channel_binding; Atrium#53). Lift with a pg8000 that fixes it.
|
||||
|
||||
# Auth
|
||||
argon2-cffi==23.1.0 # Argon2id password hashing (MIT). dredd-core depends on it too, so
|
||||
|
||||
@@ -116,8 +116,8 @@ check("USER app" in dockerfile, "container runs as root",
|
||||
|
||||
# ── the image can install the private core ────────────────────────────────────
|
||||
requirements = read("backend/requirements.txt")
|
||||
if "git+https://github.com/Alpaq92/dredd-core" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names github.com, so that could never fail.
|
||||
if "dredd-core @ git+" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names git in its URL rewrite, so that could never fail.
|
||||
# Look for git as a package of an apt/apk install (comments dropped, `\` continuations joined as
|
||||
# BuildKit joins them: whitespace may follow the backslash, and blank lines inside are skipped).
|
||||
run_text = re.sub(r"\\[ \t]*\n(?:[ \t]*\n)*", " ", re.sub(r"(?m)^\s*#.*\n", "", dockerfile))
|
||||
|
||||
@@ -157,13 +157,14 @@ def test_a_bad_json_part_is_a_422_not_a_500(api, data):
|
||||
|
||||
|
||||
def test_patch_request_passes_the_run_fields(api):
|
||||
data = {"values": {"kwota": None}, "note": "poprawka", "stage_key_seen": "s1"}
|
||||
data = {"values": {"kwota": None}, "note": "poprawka", "stage_key_seen": "s1", "round_seen": 4}
|
||||
r = api.client.patch(f"{API}/requests/{ID}", data={"data": json.dumps(data)})
|
||||
assert r.status_code == 200, r.text
|
||||
(name, args, kwargs), = api.calls
|
||||
assert name == "update" and args[2] == ID
|
||||
assert kwargs["values"] == {"kwota": None} and kwargs["note"] == "poprawka"
|
||||
assert kwargs["stage_key_seen"] == "s1" and kwargs["files"] == []
|
||||
assert kwargs["round_seen"] == 4
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -113,12 +113,13 @@ def test_start_on_a_file_and_on_a_request(api):
|
||||
|
||||
def test_actions_pass_what_the_caller_saw(api):
|
||||
r = api.client.post(f"{API}/runs/{RUN}/actions", json={
|
||||
"action": "reject", "stage_key_seen": "s1", "stages_seen": ["s1", "s2"], "note": "nie"})
|
||||
"action": "reject", "stage_key_seen": "s1", "stages_seen": ["s1", "s2"], "round_seen": 3,
|
||||
"note": "nie"})
|
||||
assert r.status_code == 200, r.text
|
||||
(_, args, kwargs), = api.calls
|
||||
assert args[2] == RUN and kwargs["action"] == "reject" and kwargs["token"] == "t-9"
|
||||
assert (kwargs["stage_key_seen"], kwargs["stages_seen"], kwargs["note"]) == (
|
||||
"s1", ["s1", "s2"], "nie")
|
||||
assert (kwargs["stage_key_seen"], kwargs["stages_seen"], kwargs["round_seen"],
|
||||
kwargs["note"]) == ("s1", ["s1", "s2"], 3, "nie")
|
||||
|
||||
|
||||
def test_add_stage_and_scan_are_their_own_actions(api):
|
||||
@@ -126,13 +127,14 @@ def test_add_stage_and_scan_are_their_own_actions(api):
|
||||
"note": "jeszcze prawnik", "stage_key_seen": "s1",
|
||||
"stage": {"name": "Prawnik", "approver": {"kind": "users", "user_ids": [str(RUN)]}}})
|
||||
assert r.status_code == 200, r.text
|
||||
r = api.client.post(f"{API}/runs/{RUN}/scan", data={"stage_key_seen": "s2"},
|
||||
r = api.client.post(f"{API}/runs/{RUN}/scan", data={"stage_key_seen": "s2", "round_seen": "2"},
|
||||
files={"file": ("skan.pdf", io.BytesIO(b"%PDF"), "application/pdf")})
|
||||
assert r.status_code == 200, r.text
|
||||
(_, _, added), (_, _, scanned) = api.calls
|
||||
assert added["action"] == "add_stage" and added["new_stage"]["name"] == "Prawnik"
|
||||
assert "key" not in added["new_stage"]
|
||||
assert scanned["action"] == "paper_scan" and scanned["stage_key_seen"] == "s2"
|
||||
assert scanned["round_seen"] == 2 and added["round_seen"] is None
|
||||
assert scanned["scan"].filename == "skan.pdf"
|
||||
assert api.db.commits == 2
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""DB-free tests of the Archive's evidence contract (Atrium#53) and the technical account's fence."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import main
|
||||
from app.config import get_settings
|
||||
from app.db import get_db
|
||||
from app.errors import NotFoundError
|
||||
from app.services import audit, authz, evidence
|
||||
from app.services import auth as auth_service
|
||||
from app.services import moderation as moderation_service
|
||||
|
||||
DOC = uuid.uuid4()
|
||||
READER = get_settings().archive_reader_id
|
||||
|
||||
|
||||
def _run(scan=None):
|
||||
return SimpleNamespace(
|
||||
id=uuid.uuid4(), ref_document_id=DOC, ref_path="umowa.pdf", ref_commit_sha="a" * 40,
|
||||
ref_sha256="b" * 64, state="zatwierdzony", round=1, started_by=uuid.uuid4(),
|
||||
template_id=None, template_name="Umowy", stages=[{"key": "s1", "name": "Prawnik"}],
|
||||
settings={}, updated_at=dt.datetime(2026, 11, 27, tzinfo=dt.timezone.utc), scan=scan)
|
||||
|
||||
|
||||
def test_timeline_is_canonical_json():
|
||||
run = _run()
|
||||
ev = SimpleNamespace(kind="approved", stage_from=0, stage_to=None, round=1,
|
||||
actor_id=run.started_by, note="ok", evidence={"commit_sha": "a" * 40},
|
||||
created_at=dt.datetime(2026, 11, 27, tzinfo=dt.timezone.utc))
|
||||
people = {run.started_by: SimpleNamespace(full_name="Ala", email="ala@x.pl")}
|
||||
one = evidence.timeline_doc(run, [ev], people)
|
||||
assert one == evidence.timeline_doc(run, [ev], people)
|
||||
doc = json.loads(one)
|
||||
assert doc["template_name"] == "Umowy" and doc["stages"][0]["key"] == "s1"
|
||||
assert doc["timeline"][0]["actor"]["name"] == "Ala" and doc["timeline"][0]["note"] == "ok"
|
||||
|
||||
|
||||
def test_items_timeline_and_scan():
|
||||
scan = {"kind": "file", "file_id": str(uuid.uuid4()), "sha256": "c" * 64, "size": 3, "name": "skan.pdf"}
|
||||
run = _run(scan)
|
||||
items = evidence.items_for(run, b"{}")
|
||||
assert [i["kind"] for i in items] == ["timeline", "paper_scan"]
|
||||
assert items[0]["sha256"] == hashlib.sha256(b"{}").hexdigest()
|
||||
assert items[0]["download"] == f"evidence/runs/{run.id}/timeline"
|
||||
assert items[1] == {"kind": "paper_scan", "name": "skan.pdf", "sha256": "c" * 64,
|
||||
"source_id": str(run.id), "commit_sha": None,
|
||||
"download": f"evidence/runs/{run.id}/scan"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def two_runs(monkeypatch):
|
||||
runs = [_run(), _run()]
|
||||
audited = []
|
||||
monkeypatch.setattr(evidence, "_finished", lambda db, d: runs)
|
||||
monkeypatch.setattr(evidence, "_timeline", lambda db, run: b"{}")
|
||||
monkeypatch.setattr(authz, "can_read_run", lambda db, user, run, token: run is runs[0])
|
||||
monkeypatch.setattr(audit, "record", lambda db, **kw: audited.append(kw))
|
||||
return runs, audited
|
||||
|
||||
|
||||
def test_person_sees_what_they_may_read_unaudited(two_runs):
|
||||
runs, audited = two_runs
|
||||
out = evidence.for_document(None, SimpleNamespace(id=uuid.uuid4()), DOC, token="t")
|
||||
assert out["module"] == "workflow" and out["document_id"] == str(DOC)
|
||||
assert [i["source_id"] for i in out["items"]] == [str(runs[0].id)]
|
||||
assert out["note"] is None and audited == []
|
||||
|
||||
|
||||
def test_technical_account_sees_all_and_is_audited(two_runs):
|
||||
runs, audited = two_runs
|
||||
out = evidence.for_document(None, SimpleNamespace(id=READER), DOC, token="t")
|
||||
assert len(out["items"]) == 2
|
||||
assert audited == [{"actor_id": READER, "action": "evidence.read", "entity_type": "document",
|
||||
"entity_id": DOC, "detail": "2 items"}]
|
||||
|
||||
|
||||
def test_nothing_is_200_with_a_note(monkeypatch):
|
||||
monkeypatch.setattr(evidence, "_finished", lambda db, d: [])
|
||||
out = evidence.for_document(None, SimpleNamespace(id=uuid.uuid4()), DOC, token="t")
|
||||
assert out["items"] == [] and out["note"]
|
||||
|
||||
|
||||
def test_fence():
|
||||
reader, person = SimpleNamespace(id=READER), SimpleNamespace(id=uuid.uuid4())
|
||||
authz.assert_archive_reader_route(reader, "/api/v1/evidence")
|
||||
authz.assert_archive_reader_route(reader, "/api/v1/evidence/runs/{run_id}/scan")
|
||||
authz.assert_archive_reader_route(person, "/api/v1/inbox")
|
||||
with pytest.raises(NotFoundError):
|
||||
authz.assert_archive_reader_route(reader, "/api/v1/inbox")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path, status", [("/api/v1/inbox", 404), ("/api/v1/auth/me", 404),
|
||||
(f"/api/v1/evidence?document_id={DOC}", 200)])
|
||||
def test_technical_account_reaches_only_evidence(monkeypatch, path, status):
|
||||
reader = SimpleNamespace(id=READER, is_admin=False, is_active=True)
|
||||
cred = SimpleNamespace(scope="read", id=uuid.uuid4(), kind="app_token")
|
||||
monkeypatch.setattr(auth_service, "resolve_session_full", lambda db, t: (reader, cred))
|
||||
monkeypatch.setattr(moderation_service, "assert_may_use", lambda db, u: None)
|
||||
monkeypatch.setattr(evidence, "for_document", lambda db, u, d, token: {"items": []})
|
||||
db = SimpleNamespace(commit=lambda: None)
|
||||
main.app.dependency_overrides[get_db] = lambda: db
|
||||
try:
|
||||
r = TestClient(main.app).get(path, headers={"Authorization": "Bearer t"})
|
||||
finally:
|
||||
main.app.dependency_overrides.clear()
|
||||
assert r.status_code == status, r.text
|
||||
@@ -83,8 +83,17 @@ def test_pinned_document_gone_keeps_run_usable(admin_client, monkeypatch):
|
||||
roles={doc: NodeRole.manager})
|
||||
monkeypatch.setattr(galena, "get", lambda: fake)
|
||||
me = admin_client.get("/api/v1/auth/me").json()["id"]
|
||||
run_id = _start(admin_client, {"kind": "document", "document_id": str(doc),
|
||||
"path": "umowa.pdf"}, me)
|
||||
# The admin approves their own run: only a template (the moderator's) may allow that.
|
||||
r = admin_client.post("/api/v1/admin/templates", json={
|
||||
"name": f"Sam {uuid.uuid4().hex[:6]}",
|
||||
"stages": [{"name": "Akceptacja", "approver": {"kind": "users", "user_ids": [me]}}],
|
||||
"settings": {"initiator_may_approve": True}})
|
||||
assert r.status_code == 201, r.text
|
||||
r = admin_client.post("/api/v1/runs", json={
|
||||
"subject": {"kind": "document", "document_id": str(doc), "path": "umowa.pdf"},
|
||||
"template_id": r.json()["id"]})
|
||||
assert r.status_code == 201, r.text
|
||||
run_id = r.json()["run_id"]
|
||||
assert admin_client.get(f"/api/v1/runs/{run_id}").json()["subject_available"] is True
|
||||
|
||||
fake.documents.clear() # the pinned version is gone from Galena
|
||||
|
||||
@@ -170,6 +170,30 @@ def test_editable_request_edit_resets_run(files):
|
||||
db.rollback()
|
||||
|
||||
|
||||
def test_a_click_from_before_an_edit_does_not_approve_the_edit(files):
|
||||
from app.db import SessionLocal
|
||||
from app.errors import ConflictError
|
||||
from app.services import requests, runs
|
||||
|
||||
with SessionLocal() as db:
|
||||
admin = _admin(db)
|
||||
approver = _approver(db)
|
||||
field, request, run = _request_in_run(db, admin, approver, editable=True)
|
||||
key = run.stages[0]["key"] # the approver reads 1000 in round 1, stage 0
|
||||
requests.update(db, admin, request.id, values={field.key: "10000"}, note="więcej",
|
||||
round_seen=1, token=TOKEN)
|
||||
db.flush()
|
||||
assert (run.current, run.round) == (0, 2) # the same stage key, a new round
|
||||
with pytest.raises(ConflictError) as err:
|
||||
runs.act(db, approver, run.id, action="approve", stage_key_seen=key, round_seen=1,
|
||||
token=TOKEN)
|
||||
assert err.value.extra["code"] == "round_changed"
|
||||
runs.act(db, approver, run.id, action="approve", stage_key_seen=key, round_seen=2,
|
||||
token=TOKEN)
|
||||
assert run.current == 1
|
||||
db.rollback()
|
||||
|
||||
|
||||
def test_approved_request_cannot_be_edited(files):
|
||||
from app.db import SessionLocal
|
||||
from app.errors import ConflictError
|
||||
|
||||
@@ -40,7 +40,8 @@ def _template(db, admin, approver_id):
|
||||
"name": f"Wydatek {uuid.uuid4().hex[:6]}",
|
||||
"stages": [{"name": "Kierownik", "approver": me, "quorum": "all"},
|
||||
{"name": "Księgowość", "approver": me}],
|
||||
"settings": {"on_reject_by_approver": "end"}})
|
||||
# The moderator's template lets the initiator approve: the admin starts and approves here.
|
||||
"settings": {"on_reject_by_approver": "end", "initiator_may_approve": True}})
|
||||
|
||||
|
||||
def test_start_copies_template_stages_and_settings(files):
|
||||
@@ -154,18 +155,20 @@ def test_two_approvals_same_stage_one_wins(files):
|
||||
|
||||
with SessionLocal() as db:
|
||||
admin = _admin(db)
|
||||
run = _two_stages(db, admin, admin.id, admin.id)
|
||||
approver_id = _person(db, "zatwierdzajacy").id # the initiator may not approve by default
|
||||
run = _two_stages(db, admin, approver_id, approver_id)
|
||||
run_id, key = run.id, run.stages[0]["key"]
|
||||
db.commit() # both sessions below must see the run; it is cancelled at the end
|
||||
|
||||
barrier, outcomes = threading.Barrier(2), []
|
||||
|
||||
def approve():
|
||||
from app.models import AppUser
|
||||
with SessionLocal() as db:
|
||||
barrier.wait()
|
||||
try:
|
||||
runs.act(db, _admin(db), run_id, action="approve", stage_key_seen=key,
|
||||
token=TOKEN)
|
||||
runs.act(db, db.get(AppUser, approver_id), run_id, action="approve",
|
||||
stage_key_seen=key, token=TOKEN)
|
||||
db.commit()
|
||||
outcomes.append("ok")
|
||||
except ConflictError as err:
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Importing Galena's approval runs as history: the mapping and the import, DB-free."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.models.workflow import WorkflowEvent, WorkflowRun, WorkflowTemplate
|
||||
from app.services import legacy_import as li
|
||||
|
||||
ALICE, BOB = str(uuid.uuid4()), str(uuid.uuid4())
|
||||
DOC = str(uuid.uuid4())
|
||||
COMMIT, SHA = "a" * 40, "b" * 64
|
||||
STAGES = [{"key": "prawny", "name": "Przegląd prawny", "type": "przeglad_tresci",
|
||||
"approver": {"kind": "role", "role": "approver"}},
|
||||
{"key": "akceptacja", "name": "Akceptacja",
|
||||
"approver": {"kind": "users", "user_ids": [BOB]}}]
|
||||
|
||||
|
||||
class _Db:
|
||||
"""Enough of a Session: nothing exists yet, and `people` are the accounts that do."""
|
||||
|
||||
def __init__(self, people=(ALICE, BOB), existing=()):
|
||||
self.people = {uuid.UUID(p) for p in people}
|
||||
self.existing = set(existing)
|
||||
self.added: list = []
|
||||
self.queries = 0
|
||||
|
||||
def get(self, _model, key):
|
||||
return object() if key in self.existing else None
|
||||
|
||||
def scalars(self, stmt):
|
||||
self.queries += 1
|
||||
if "app_user" in str(stmt):
|
||||
return list(self.people)
|
||||
return list(self.existing)
|
||||
|
||||
def add(self, obj):
|
||||
self.added.append(obj)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_audit(monkeypatch):
|
||||
monkeypatch.setattr(li.audit, "record", lambda *a, **k: None)
|
||||
|
||||
|
||||
def _export(**run_changes):
|
||||
run = {"id": str(uuid.uuid4()), "node_id": DOC, "commit_sha": COMMIT,
|
||||
"template_id": "t1", "template_name": "Przegląd i akceptacja", "stages": STAGES,
|
||||
"initiator_may_approve": False, "state": "zatwierdzony", "started_by": ALICE,
|
||||
"created_at": "2026-10-01T09:00:00+00:00", "updated_at": "2026-10-02T09:00:00+00:00",
|
||||
"scan": None,
|
||||
"subject": {"document_id": DOC, "path": "umowa.docx", "commit_sha": COMMIT, "sha256": SHA},
|
||||
"skipped": None,
|
||||
"events": [
|
||||
{"id": "e1", "kind": "start", "stage": 0, "actor_id": ALICE, "note": None,
|
||||
"evidence": None, "created_at": "2026-10-01T09:00:00+00:00"},
|
||||
{"id": "e2", "kind": "zatwierdzenie", "stage": 0, "actor_id": BOB, "note": None,
|
||||
"evidence": COMMIT, "created_at": "2026-10-01T10:00:00+00:00"},
|
||||
{"id": "e3", "kind": "zatwierdzenie", "stage": 1, "actor_id": BOB, "note": "ok",
|
||||
"evidence": None, "created_at": "2026-10-02T09:00:00+00:00"},
|
||||
{"id": "e4", "kind": "zakonczenie", "stage": 1, "actor_id": BOB, "note": None,
|
||||
"evidence": None, "created_at": "2026-10-02T09:00:00+00:00"}]}
|
||||
run.update(run_changes)
|
||||
return {"format": li.FORMAT,
|
||||
"templates": [{"id": "t1", "name": "Przegląd i akceptacja", "stages": STAGES,
|
||||
"initiator_may_approve": False, "archived": False,
|
||||
"created_at": "2026-09-01T09:00:00+00:00"}],
|
||||
"runs": [run], "in_progress": []}
|
||||
|
||||
|
||||
def test_ids_are_stable_and_distinct_per_kind():
|
||||
assert li.new_id("run", "x") == li.new_id("run", "x")
|
||||
assert li.new_id("run", "x") != li.new_id("template", "x")
|
||||
|
||||
|
||||
def test_stages_keep_keys_names_types_and_approvers():
|
||||
out = li.stages_of(STAGES)
|
||||
assert [s["key"] for s in out] == ["prawny", "akceptacja"]
|
||||
assert out[0]["type"] == "przeglad_tresci" and out[0]["approver"]["kind"] == "role"
|
||||
assert all(s["quorum"] == "one" for s in out)
|
||||
|
||||
|
||||
def test_evidence_and_where_an_event_left_the_run():
|
||||
assert li.evidence_of(COMMIT) == {"commit_sha": COMMIT}
|
||||
assert li.evidence_of(SHA) == {"sha256": SHA}
|
||||
assert li.evidence_of(None) is None and li.evidence_of("x") is None
|
||||
assert li.stage_to("start", 0, 2) == 0
|
||||
assert li.stage_to("zatwierdzenie", 0, 2) == 1
|
||||
assert li.stage_to("zatwierdzenie", 1, 2) is None
|
||||
assert li.stage_to("odrzucenie", 0, 2) is None
|
||||
|
||||
|
||||
def test_a_finished_run_comes_in_as_history():
|
||||
db = _Db()
|
||||
report = li.import_export(db, _export())
|
||||
assert (report.templates, report.runs, report.skipped) == (1, 1, [])
|
||||
template = next(o for o in db.added if isinstance(o, WorkflowTemplate))
|
||||
run = next(o for o in db.added if isinstance(o, WorkflowRun))
|
||||
events = [o for o in db.added if isinstance(o, WorkflowEvent)]
|
||||
# The template follows THIS module's rejection rule; the run keeps the old one ("end").
|
||||
assert template.settings["on_reject_by_approver"] == "previous"
|
||||
assert run.settings["on_reject_by_owner"] == run.settings["on_reject_by_approver"] == "end"
|
||||
assert run.settings["initiator_may_approve"] is False
|
||||
assert (run.state, run.current, run.round) == ("zatwierdzony", None, 1)
|
||||
assert (run.ref_document_id, run.ref_path, run.ref_sha256) == (uuid.UUID(DOC), "umowa.docx", SHA)
|
||||
assert run.template_id == template.id
|
||||
assert [(e.kind, e.stage_from, e.stage_to) for e in events] == [
|
||||
("start", None, 0), ("zatwierdzenie", 0, 1), ("zatwierdzenie", 1, None),
|
||||
("zakonczenie", 1, None)]
|
||||
assert events[1].evidence == {"commit_sha": COMMIT}
|
||||
|
||||
|
||||
def test_a_second_import_adds_nothing():
|
||||
first = _export()
|
||||
run_id = li.new_id("run", first["runs"][0]["id"])
|
||||
db = _Db(existing={run_id, li.new_id("template", "t1")})
|
||||
report = li.import_export(db, first)
|
||||
assert (report.templates, report.runs, report.already) == (0, 0, 2) and db.added == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change, reason", [
|
||||
({"subject": None, "skipped": "no_single_document_file"}, "not pinned by the export"),
|
||||
({"state": "w_toku"}, "is not a finished one"),
|
||||
({"started_by": str(uuid.uuid4())}, "no longer exists"),
|
||||
])
|
||||
def test_what_cannot_be_imported_is_reported_not_written(change, reason):
|
||||
db = _Db()
|
||||
report = li.import_export(db, _export(**change))
|
||||
assert report.runs == 0 and reason in report.skipped[0]
|
||||
assert not [o for o in db.added if isinstance(o, WorkflowRun | WorkflowEvent)]
|
||||
|
||||
|
||||
def test_not_a_galena_export_is_refused():
|
||||
with pytest.raises(ValidationError):
|
||||
li.import_export(_Db(), {"format": "something-else"})
|
||||
|
||||
|
||||
def test_nothing_is_emitted_or_notified():
|
||||
import inspect
|
||||
source = inspect.getsource(li)
|
||||
assert "events.emit" not in source and "notify." not in source
|
||||
|
||||
|
||||
def test_a_paper_ending_with_its_scan_is_signed_not_approved():
|
||||
"""The old engine had no "signed": its approved run ending with a paper scan is `podpisany` here."""
|
||||
paper = [{"type": "zatwierdzenie"}, {"type": "podpis_papierowy"}]
|
||||
scan = {"kind": "document"}
|
||||
assert li.state_of("zatwierdzony", scan, paper) == "podpisany"
|
||||
assert li.state_of("zatwierdzony", None, paper) == "zatwierdzony"
|
||||
assert li.state_of("zatwierdzony", scan, [{"type": "zatwierdzenie"}]) == "zatwierdzony"
|
||||
assert li.state_of("odrzucony", scan, paper) == "odrzucony"
|
||||
|
||||
|
||||
def test_an_imported_scan_reads_back_as_a_document_ref():
|
||||
from dredd_core.document_ref import DocumentRef, from_dict
|
||||
|
||||
db = _Db()
|
||||
li.import_export(db, _export(scan={"path": "podpisane/umowa.pdf", "commit_sha": "c" * 40,
|
||||
"sha256": "d" * 64}))
|
||||
run = next(o for o in db.added if isinstance(o, WorkflowRun))
|
||||
ref = from_dict(run.scan)
|
||||
assert isinstance(ref, DocumentRef) and ref.path == "podpisane/umowa.pdf"
|
||||
|
||||
|
||||
def _runs(db):
|
||||
return [o for o in db.added if isinstance(o, WorkflowRun)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", [
|
||||
{"started_by": "not-a-uuid"},
|
||||
{"started_by": None},
|
||||
{"events": [{"id": "e1", "kind": "start", "stage": 0}]}, # no actor_id
|
||||
{"node_id": None, "initiator_may_approve": None, "template_name": None} ,
|
||||
{"subject": {"document_id": DOC}}, # no path
|
||||
{"stages": "nonsense"},
|
||||
])
|
||||
def test_a_malformed_run_is_skipped_and_the_rest_imported(change):
|
||||
data = _export(**change)
|
||||
good = _export()["runs"][0]
|
||||
data["runs"].append(good)
|
||||
data["runs"].append("not an object")
|
||||
if "template_name" in change:
|
||||
del data["runs"][0]["template_name"]
|
||||
db = _Db()
|
||||
report = li.import_export(db, data)
|
||||
assert report.runs == 1 and len(report.skipped) == 2
|
||||
assert [r.id for r in _runs(db)] == [li.new_id("run", good["id"])]
|
||||
|
||||
|
||||
def test_a_malformed_template_is_skipped_not_fatal():
|
||||
data = _export()
|
||||
data["templates"].append({"name": "bez id"})
|
||||
data["templates"].append({"id": "t2", "name": "x", "stages": STAGES}) # no initiator_may_approve
|
||||
db = _Db()
|
||||
report = li.import_export(db, data)
|
||||
assert (report.templates, report.runs, len(report.skipped)) == (1, 1, 2)
|
||||
|
||||
|
||||
def test_an_unknown_event_kind_skips_only_that_run():
|
||||
bad = _export()["runs"][0]
|
||||
bad["events"][1]["kind"] = "delegacja"
|
||||
data = _export()
|
||||
data["runs"].insert(0, bad)
|
||||
db = _Db()
|
||||
report = li.import_export(db, data)
|
||||
assert report.runs == 1 and "unknown event kind 'delegacja'" in report.skipped[0]
|
||||
assert len(_runs(db)) == 1
|
||||
assert {e.run_id for e in db.added if isinstance(e, WorkflowEvent)} == {_runs(db)[0].id}
|
||||
|
||||
|
||||
def test_existence_is_read_once_for_the_whole_file():
|
||||
data = _export()
|
||||
data["runs"] += [_export()["runs"][0] for _ in range(5)]
|
||||
db = _Db()
|
||||
li.import_export(db, data)
|
||||
assert db.queries == 3 and len(_runs(db)) == 6
|
||||
|
||||
|
||||
def test_a_role_approver_stage_is_imported():
|
||||
db = _Db()
|
||||
li.import_export(db, _export())
|
||||
run = _runs(db)[0]
|
||||
assert run.stages[0]["approver"] == {"kind": "role", "role": "approver"}
|
||||
template = next(o for o in db.added if isinstance(o, WorkflowTemplate))
|
||||
assert template.stages[0]["approver"]["kind"] == "role"
|
||||
|
||||
|
||||
def test_an_approved_run_ending_on_paper_with_its_scan_is_imported_signed():
|
||||
paper = [STAGES[1], {"key": "papier", "name": "Podpis", "type": "podpis_papierowy",
|
||||
"approver": {"kind": "users", "user_ids": [ALICE]}}]
|
||||
db = _Db()
|
||||
report = li.import_export(db, _export(
|
||||
stages=paper, scan={"path": "skan.pdf", "commit_sha": "c" * 40, "sha256": "d" * 64}))
|
||||
assert report.skipped == []
|
||||
assert _runs(db)[0].state == "podpisany"
|
||||
@@ -156,6 +156,33 @@ def test_notify_on_reject_values():
|
||||
assert rules.merge_settings({"notify_on_reject": []})["notify_on_reject"] == []
|
||||
|
||||
|
||||
def test_the_initiator_lock_is_on_by_default():
|
||||
assert rules.DEFAULT_SETTINGS["initiator_may_approve"] is False
|
||||
|
||||
|
||||
def test_a_run_override_may_not_lift_the_initiator_lock():
|
||||
locked = rules.merge_settings({"initiator_may_approve": False})
|
||||
for base in (None, locked):
|
||||
with pytest.raises(ValidationError) as e:
|
||||
rules.merge_settings({"initiator_may_approve": True}, base, for_run=True)
|
||||
assert code(e) == "initiator_lock_fixed"
|
||||
# Keeping the lock, or laying anything else over it, is fine.
|
||||
out = rules.merge_settings({"initiator_may_approve": False, "resolve": "live"}, locked,
|
||||
for_run=True)
|
||||
assert out["initiator_may_approve"] is False and out["resolve"] == "live"
|
||||
|
||||
|
||||
def test_a_template_may_let_the_initiator_approve_and_a_run_may_lock_it_again():
|
||||
# A template's own settings are a moderator's: no for_run there.
|
||||
allowing = rules.merge_settings({"initiator_may_approve": True})
|
||||
assert allowing["initiator_may_approve"] is True
|
||||
assert rules.merge_settings({"initiator_may_approve": True}, allowing,
|
||||
for_run=True)["initiator_may_approve"] is True
|
||||
assert rules.merge_settings({"initiator_may_approve": False}, allowing,
|
||||
for_run=True)["initiator_may_approve"] is False
|
||||
assert rules.merge_settings(None, allowing, for_run=True)["initiator_may_approve"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sent", [
|
||||
{"notify_on_reject": ["boss"]}, {"notify_on_reject": ["user:nope"]}, {"notify_on_reject": "owner"},
|
||||
{"on_reject_by_owner": "later"}, {"on_reject_by_approver": None}, {"resolve": "sometimes"},
|
||||
|
||||
@@ -176,7 +176,8 @@ class _RacedDb(_Db):
|
||||
"""A start that passes the check, then loses the insert to a concurrent start."""
|
||||
|
||||
def __init__(self, constraint: str) -> None:
|
||||
super().__init__()
|
||||
# The stage's person exists: the start must get past every check to reach the insert.
|
||||
super().__init__(objects={OTHER: SimpleNamespace(id=OTHER, is_active=True, is_admin=False)})
|
||||
self.constraint = constraint
|
||||
|
||||
def flush(self):
|
||||
@@ -277,6 +278,31 @@ def test_initiator_lock_refuses_a_stage_only_the_initiator_approves():
|
||||
assert err.value.extra["code"] == "initiator_only_approver"
|
||||
|
||||
|
||||
def test_initiator_lock_is_on_without_a_template():
|
||||
# Own stages naming only the initiator: nobody else could approve, and they may not.
|
||||
with pytest.raises(ValidationError) as err:
|
||||
runs.start(_Db(), _actor(), subject=FILE, stages=[_users(ME)], token=TOKEN)
|
||||
assert err.value.extra["code"] == "initiator_only_approver"
|
||||
|
||||
|
||||
def test_the_initiator_may_not_lift_the_lock_when_starting():
|
||||
with pytest.raises(ValidationError) as err:
|
||||
runs.start(_Db(), _actor(), subject=FILE, stages=[_users(ME)],
|
||||
settings_override={"initiator_may_approve": True}, token=TOKEN)
|
||||
assert err.value.extra["code"] == "initiator_lock_fixed"
|
||||
template = SimpleNamespace(id=uuid.uuid4(), name="Wydatek", archived=False,
|
||||
settings=dict(runs.rules.DEFAULT_SETTINGS),
|
||||
stages=[{"key": "k", "name": "Kierownik", "type": "zatwierdzenie",
|
||||
"approver": {"kind": "users", "user_ids": [str(OTHER)]},
|
||||
"quorum": "one"}])
|
||||
db = _Db(objects={template.id: template})
|
||||
with pytest.raises(ValidationError) as err:
|
||||
runs.start(db, _actor(), subject=FILE, template_id=template.id, stages=[_users(ME)],
|
||||
settings_override={"initiator_may_approve": True}, token=TOKEN)
|
||||
assert err.value.extra["code"] == "initiator_lock_fixed"
|
||||
assert db.writes == []
|
||||
|
||||
|
||||
def test_unknown_subject_is_422():
|
||||
with pytest.raises(ValidationError) as err:
|
||||
runs.start(_Db(), _actor(), subject={"kind": "file"}, stages=[_users(OTHER)], token=TOKEN)
|
||||
@@ -367,6 +393,28 @@ def test_act_409_stale_stages(monkeypatch, seen):
|
||||
assert err.value.extra["code"] == "stages_changed"
|
||||
|
||||
|
||||
def test_assert_current_refuses_a_click_from_another_round():
|
||||
# An edit of the request or a rejection on the first stage brings the run back to the SAME
|
||||
# stage key in a new round: the key alone would let a click from before approve what came after.
|
||||
run = _run(current=0, round=2)
|
||||
runs.assert_current(run, action="approve", stage_key_seen="a", stages_seen=["a", "b"],
|
||||
round_seen=2)
|
||||
runs.assert_current(run, action="approve", stage_key_seen="a", stages_seen=None) # not sent
|
||||
for stale in (1, 3, True, "2"):
|
||||
with pytest.raises(ConflictError) as err:
|
||||
runs.assert_current(run, action="approve", stage_key_seen="a", stages_seen=None,
|
||||
round_seen=stale)
|
||||
assert err.value.extra["code"] == "round_changed"
|
||||
|
||||
|
||||
def test_act_409_stale_round_before_403(monkeypatch):
|
||||
db = _acting(monkeypatch) # round 1; LATER may not approve stage a, so the 409 comes first
|
||||
with pytest.raises(ConflictError) as err:
|
||||
_act(db, LATER, round_seen=0)
|
||||
assert err.value.extra["code"] == "round_changed"
|
||||
assert db.writes == []
|
||||
|
||||
|
||||
def test_cancel_checks_the_stage_only_when_sent(monkeypatch):
|
||||
db = _acting(monkeypatch)
|
||||
with pytest.raises(ConflictError) as err:
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Galena's "Send for approval" lands here: the new-run screen takes the document from the link,
|
||||
locked, and still lets the server re-pin it. Rendered under Node with the screen's helpers stubbed."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
CONSOLE = pathlib.Path(__file__).resolve().parents[2] / "frontend" / "app.js"
|
||||
SRC = CONSOLE.read_text(encoding="utf-8")
|
||||
NODE = shutil.which("node")
|
||||
|
||||
|
||||
def _fn(head: str) -> str:
|
||||
start = SRC.index(head)
|
||||
return SRC[start:SRC.index("\n}\n", start) + 3]
|
||||
|
||||
|
||||
def _esc() -> str:
|
||||
start = SRC.index("const esc = ")
|
||||
return SRC[start:SRC.index(";\n", start) + 2]
|
||||
|
||||
|
||||
def _render(q: dict, galena: bool = True) -> dict[str, dict]:
|
||||
"""Run viewNewRun(C, q) and return its inputs by id: {id: {value, readonly}}."""
|
||||
script = (
|
||||
f"{_esc()}\n"
|
||||
f"const api = async () => ({{ galena_enabled: {json.dumps(galena)} }});\n"
|
||||
"const loadStart = async () => {}; const setCrumb = () => {}; const layoutChanged = () => {};\n"
|
||||
"const state = { start: {} }; const stepHead = (n) => `<h2>${n}</h2>`;\n"
|
||||
"const layoutPicker = () => ''; const stepFoot = () => '';\n"
|
||||
f"{_fn('async function viewNewRun(C, q) {')}\n"
|
||||
f"const C = {{ innerHTML: '' }};\n"
|
||||
f"viewNewRun(C, {json.dumps(q)}).then(() => console.log(C.innerHTML));")
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
|
||||
encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
out = {}
|
||||
for tag in re.findall(r"<input[^>]*>", r.stdout):
|
||||
ident = re.search(r'id="([^"]+)"', tag).group(1)
|
||||
value = re.search(r'value="([^"]*)"', tag)
|
||||
out[ident] = {"value": value.group(1) if value else None, "readonly": " readonly" in tag}
|
||||
return out
|
||||
|
||||
|
||||
needs_node = pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
|
||||
|
||||
@needs_node
|
||||
def test_the_link_fills_both_fields_locked_and_escaped():
|
||||
inputs = _render({"kind": "document", "document_id": "d1", "path": 'umowy/"a"<b>.pdf'})
|
||||
assert inputs["nsDocId"] == {"value": "d1", "readonly": True}
|
||||
assert inputs["nsDocPath"] == {"value": "umowy/"a"<b>.pdf", "readonly": True}
|
||||
|
||||
|
||||
@needs_node
|
||||
@pytest.mark.parametrize("q", [
|
||||
{"kind": "document", "document_id": "d1"},
|
||||
{"kind": "document", "path": "a.pdf"},
|
||||
{"kind": "document"},
|
||||
])
|
||||
def test_locked_only_when_both_came_with_the_link(q):
|
||||
inputs = _render(q)
|
||||
assert not inputs["nsDocId"]["readonly"] and not inputs["nsDocPath"]["readonly"]
|
||||
assert inputs["nsDocId"]["value"] == q.get("document_id", "")
|
||||
assert inputs["nsDocPath"]["value"] == q.get("path", "")
|
||||
|
||||
|
||||
@needs_node
|
||||
def test_without_galena_it_is_an_upload():
|
||||
inputs = _render({"kind": "document", "document_id": "d1", "path": "a.pdf"}, galena=False)
|
||||
assert set(inputs) == {"nsFile"}
|
||||
|
||||
|
||||
def test_the_start_still_sends_id_and_path_for_the_server_to_pin():
|
||||
start = _fn("function startRun(e) {")
|
||||
assert "document_id: $('nsDocId').value.trim(), path: $('nsDocPath').value.trim()" in start
|
||||
|
||||
|
||||
def test_the_new_sentence_is_translated():
|
||||
assert "'Dokument wybrany w Galenie. Obieg zatwierdzi jego obecną wersję główną.': " in SRC
|
||||
@@ -0,0 +1,50 @@
|
||||
"""An approved run hands its document to Parafa ("przekazanie do Parafy"). The link is
|
||||
built in the console; asserted on the source, and under Node where it exists."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
FN = SRC[SRC.index("function signingUrl("):SRC.index("\n}\n", SRC.index("function signingUrl(")) + 3]
|
||||
DOC = {"document_id": "d1", "path": "umowy/najem.pdf", "commit_sha": "a" * 40}
|
||||
|
||||
|
||||
def _url(run: dict, hub: bool = True):
|
||||
script = (f"const hubMode = () => {json.dumps(hub)};\n{FN}\n"
|
||||
f"console.log(JSON.stringify(signingUrl({json.dumps(run)})));")
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
|
||||
encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_an_approved_galena_pdf_goes_to_parafa_at_the_approved_commit() -> None:
|
||||
url = _url({"state": "zatwierdzony", "subject_kind": "document", "subject": DOC, "title": "Najem"})
|
||||
assert url.startswith("../parafa/#/new?") and "version=" + "a" * 40 in url
|
||||
assert "document_id=d1" in url and "path=umowy%2Fnajem.pdf" in url
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
@pytest.mark.parametrize("run, hub", [
|
||||
({"state": "w_toku", "subject_kind": "document", "subject": DOC}, True),
|
||||
({"state": "podpisany", "subject_kind": "document", "subject": DOC}, True),
|
||||
({"state": "zatwierdzony", "subject_kind": "document", "subject": {**DOC, "path": "a.docx"}}, True),
|
||||
({"state": "zatwierdzony", "subject_kind": "file", "subject": {"file_id": "f"}}, True),
|
||||
({"state": "zatwierdzony", "subject_kind": "document", "subject": DOC}, False),
|
||||
])
|
||||
def test_otherwise_no_link(run, hub) -> None:
|
||||
assert _url(run, hub) is None
|
||||
|
||||
|
||||
def test_the_button_is_in_the_action_bar() -> None:
|
||||
assert "const sign = signingUrl(r);" in SRC and "Wyślij do podpisu" in SRC
|
||||
# A plain button: the stage's own approval stays the one primary action.
|
||||
assert '<a class="btn" href="${esc(sign)}">' in SRC
|
||||
@@ -1,7 +1,7 @@
|
||||
# Workflow on a managed PostgreSQL database (the family's shared one, or any Postgres 16/17 reached
|
||||
# over a network): an override for docker-compose.yml.
|
||||
#
|
||||
# DREDD_CORE_TOKEN=github_pat_... \
|
||||
# DREDD_CORE_TOKEN=<read-only Gitea token> \
|
||||
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
|
||||
#
|
||||
# The database lives elsewhere — the family shares ONE managed database, and Workflow has schema
|
||||
|
||||
+1
-1
@@ -63,6 +63,6 @@ secrets:
|
||||
# Used only by the build stage's one `pip install`; no running container gets it. Compose resolves
|
||||
# the variable from the shell OR the project .env (shell wins) — keep it in the shell, because every
|
||||
# service here also loads .env at runtime and would receive the token:
|
||||
# DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build
|
||||
# DREDD_CORE_TOKEN=<read-only Gitea token> docker compose up -d --build
|
||||
dredd_core_token:
|
||||
environment: DREDD_CORE_TOKEN
|
||||
|
||||
+43
-12
@@ -343,6 +343,7 @@ const I18N = {
|
||||
'Wgraj plik': 'Upload a file',
|
||||
'Identyfikator dokumentu': 'Document ID',
|
||||
'Ścieżka dokumentu': 'Document path',
|
||||
'Dokument wybrany w Galenie. Obieg zatwierdzi jego obecną wersję główną.': 'Document chosen in Galena. The run approves its current main version.',
|
||||
'Rozpocznij obieg': 'Start the run',
|
||||
'Wybierz plik.': 'Choose a file.',
|
||||
'Moderator nie zdefiniował jeszcze typów wniosków.': 'A moderator has not defined any request types yet.',
|
||||
@@ -356,6 +357,7 @@ const I18N = {
|
||||
'Cofnij': 'Send back',
|
||||
'Anuluj obieg': 'Cancel the run',
|
||||
'Edytuj wniosek': 'Edit the request',
|
||||
'Wyślij do podpisu': 'Send for signing',
|
||||
'Bieżący etap': 'Current stage',
|
||||
'Runda': 'Round',
|
||||
'Oś czasu': 'Timeline',
|
||||
@@ -781,7 +783,7 @@ function layoutChanged() {
|
||||
$('lpPreview').classList.toggle('hidden', own);
|
||||
$('lpEditor').innerHTML = !own ? '' : `<div class="field" style="margin:16px 0 8px">Etapy</div>
|
||||
${stageEditor('lpStages', t ? t.stages : [], { allowRole: state.start.allowRole, groups: state.start.groups })}
|
||||
${settingsEditor('lpSet', t ? t.settings : null)}
|
||||
${settingsEditor('lpSet', t ? t.settings : null, true)}
|
||||
${isModerator() ? `<div class="row" style="margin-top:12px"><button type="button" class="btn" onclick="saveLayoutAsTemplate()">${svg(ICN.plus)}Zapisz jako szablon</button></div>` : ''}`;
|
||||
localize($('lpEditor'));
|
||||
}
|
||||
@@ -853,18 +855,24 @@ const stepFoot = (label) => `<div class="form-foot"><a class="btn" href="#/new">
|
||||
<button class="btn primary" type="submit">${label}</button></div>`;
|
||||
|
||||
/* Nowa sprawa, a document: an upload, or a Galena document by id and path, re-pinned by the server
|
||||
at start. A Galena role is a stage only a document can have, so the editor offers it only then. */
|
||||
at start. A Galena role is a stage only a document can have, so the editor offers it only then.
|
||||
Galena's "Send for approval" opens this screen as
|
||||
`#/runs/new?kind=document&document_id=…&path=…`: the document arrives chosen and locked, and the
|
||||
server still re-pins it with the person's token, so the link grants nothing by itself. */
|
||||
async function viewNewRun(C, q) {
|
||||
const [opts] = await Promise.all([api('GET', '/options'), loadStart()]);
|
||||
const doc = q.kind === 'document' && !!opts.galena_enabled;
|
||||
const name = doc ? 'Dokument z Galeny' : 'Plik z komputera';
|
||||
const sent = doc && !!q.document_id && !!q.path;
|
||||
setCrumb([{ label: 'Nowa sprawa', href: '#/new' }, { label: name }]);
|
||||
state.start.allowRole = doc;
|
||||
const ro = sent ? ' readonly' : '';
|
||||
C.innerHTML = stepHead(esc(name))
|
||||
+ `<form data-errors onsubmit="startRun(event)"><div class="split">
|
||||
<div class="card form"><h3>Przedmiot obiegu</h3>${doc
|
||||
? `<label class="field">Identyfikator dokumentu<input id="nsDocId" class="mono" /></label>
|
||||
<label class="field">Ścieżka dokumentu<input id="nsDocPath" class="mono" /></label>`
|
||||
? `${sent ? '<div class="faint tiny" style="margin-bottom:8px">Dokument wybrany w Galenie. Obieg zatwierdzi jego obecną wersję główną.</div>' : ''}
|
||||
<label class="field">Ścieżka dokumentu<input id="nsDocPath" class="mono" value="${esc(q.path || '')}"${ro} /></label>
|
||||
<label class="field">Identyfikator dokumentu<input id="nsDocId" class="mono" value="${esc(q.document_id || '')}"${ro} /></label>`
|
||||
: '<label class="field">Plik<input type="file" id="nsFile" /></label>'}</div>
|
||||
${layoutPicker(null)}</div>${stepFoot('Rozpocznij obieg')}</form>`;
|
||||
layoutChanged();
|
||||
@@ -964,10 +972,15 @@ const ACTION = { // [label, note required] — rules.NOTE_REQUIRED
|
||||
approve: ['Zatwierdź', false], paper_scan: ['Zatwierdź ze skanem', false], reject: ['Odrzuć', true],
|
||||
back: ['Cofnij', true], cancel: ['Anuluj obieg', true], refresh: ['Odśwież zatwierdzających', false],
|
||||
};
|
||||
const STALE = ['stage_changed', 'stages_changed', 'not_running'];
|
||||
const STALE = ['stage_changed', 'stages_changed', 'round_changed', 'not_running'];
|
||||
const shortHash = (h) => (h ? String(h).slice(0, 12) : '');
|
||||
const stageAt = (i) => (i == null ? null : _run.stages[i]);
|
||||
const seen = () => ({ stage_key_seen: _run.stages[_run.current].key, stages_seen: _run.stages.map((s) => s.key) });
|
||||
/* The round too: a run sent back to the same stage (a request edit, a rejection on the first stage)
|
||||
keeps its stage key, and a click from before must not approve what came after. */
|
||||
const seen = () => ({
|
||||
stage_key_seen: _run.stages[_run.current].key, stages_seen: _run.stages.map((s) => s.key),
|
||||
round_seen: _run.round,
|
||||
});
|
||||
|
||||
/* runs.pinned: what a content review confirms — a document's commit, else the file's hash, else
|
||||
(a request) the snapshot hash on the newest timeline entry, since an edit re-snapshots it. */
|
||||
@@ -999,6 +1012,19 @@ async function viewRun(C, id) {
|
||||
+ `<div class="run-grid"><div>${subjectCard()}</div><div>${timelineCard()}</div></div>`;
|
||||
}
|
||||
|
||||
/* Handing an approved document to signing: Parafa's new request
|
||||
with the Galena document prefilled AT THE COMMIT THIS RUN APPROVED (`version`), so exactly the approved
|
||||
bytes are signed. Platform only (Parafa at ../parafa/), an approved run on a Galena PDF only: Parafa
|
||||
signs PDFs, and a paper ending (`podpisany`) is already signed. */
|
||||
function signingUrl(r) {
|
||||
const s = r.subject || {};
|
||||
if (!hubMode() || r.state !== 'zatwierdzony' || r.subject_kind !== 'document') return null;
|
||||
if (!s.document_id || !s.path || !/\.pdf$/i.test(s.path)) return null;
|
||||
const q = new URLSearchParams({ document_id: s.document_id, path: s.path, title: r.title || '' });
|
||||
if (s.commit_sha) q.set('version', s.commit_sha);
|
||||
return '../parafa/#/new?' + q.toString();
|
||||
}
|
||||
|
||||
/* The action bar, in the page head: only what the flags allow, the stage's own way of approving
|
||||
last (the primary one, where the eye ends). */
|
||||
function runActions() {
|
||||
@@ -1006,6 +1032,8 @@ function runActions() {
|
||||
const stage = stageAt(r.current);
|
||||
const b = (action, primary) => `<button class="btn${primary ? ' primary' : ''}" onclick="openAction('${action}')">${esc(ACTION[action][0])}</button>`;
|
||||
const out = [];
|
||||
const sign = signingUrl(r);
|
||||
if (sign) out.push(`<a class="btn" href="${esc(sign)}">${svg(ICN.check)}Wyślij do podpisu</a>`);
|
||||
if (mayEditRequest()) out.push(`<button class="btn" onclick="openEditRequest()">Edytuj wniosek</button>`);
|
||||
if (r.can_add_stage) out.push(`<button class="btn" onclick="guard(openAddStage)">${svg(ICN.plus)}Dodaj etap</button>`);
|
||||
if (r.can_refresh) out.push(b('refresh'));
|
||||
@@ -1160,6 +1188,7 @@ function doAction(action) {
|
||||
form.append('file', file);
|
||||
form.append('stage_key_seen', s.stage_key_seen);
|
||||
s.stages_seen.forEach((k) => form.append('stages_seen', k));
|
||||
form.append('round_seen', String(s.round_seen));
|
||||
if (note) form.append('note', note);
|
||||
await apiForm(`/runs/${id}/scan`, form);
|
||||
return;
|
||||
@@ -1249,7 +1278,7 @@ const MAX_STAGES = 10;
|
||||
authority (a template saved from here carries every key explicitly). */
|
||||
const DEFAULT_RUN_SETTINGS = {
|
||||
on_reject_by_owner: 'first', on_reject_by_approver: 'previous', notify_on_reject: ['owner'],
|
||||
resolve: 'on_enter', initiator_may_approve: true,
|
||||
resolve: 'on_enter', initiator_may_approve: false,
|
||||
};
|
||||
|
||||
/* One editor per container id; the start screens and "Dodaj etap" reuse it. The rows live in the
|
||||
@@ -1338,13 +1367,15 @@ function moveStage(id, i, d) {
|
||||
setStages(id, s);
|
||||
}
|
||||
|
||||
/* §5.2a „Ustawienia obiegu”, collapsed by default: most templates never touch them. */
|
||||
function settingsEditor(id, current) {
|
||||
/* §5.2a „Ustawienia obiegu”, collapsed by default: most templates never touch them. `forRun`: the
|
||||
start screen, where the initiator may keep or switch on the template's initiator lock but never
|
||||
lift it (rules.merge_settings for_run) - so the box is off and disabled when the base locks. */
|
||||
function settingsEditor(id, current, forRun) {
|
||||
const s = Object.assign({}, DEFAULT_RUN_SETTINGS, current);
|
||||
const n = s.notify_on_reject || [];
|
||||
const people = n.filter((t) => t.startsWith('user:')).map((t) => t.slice(5));
|
||||
const box = (f, on, label) =>
|
||||
`<label class="row"><input type="checkbox" data-f="${f}"${on ? ' checked' : ''} />${label}</label>`;
|
||||
const box = (f, on, label, off) =>
|
||||
`<label class="row"><input type="checkbox" data-f="${f}"${on ? ' checked' : ''}${off ? ' disabled' : ''} />${label}</label>`;
|
||||
return `<details id="${id}" class="adv"><summary>Zaawansowane</summary>
|
||||
<div class="grid2">
|
||||
<label class="field">Gdy odrzuca inicjator lub zarządca<select data-f="owner">${options(REJECT_TO, s.on_reject_by_owner)}</select></label>
|
||||
@@ -1355,7 +1386,7 @@ function settingsEditor(id, current) {
|
||||
${box('n_owner', n.includes('owner'), 'Właściciel obiegu')}
|
||||
${box('n_initiator', n.includes('initiator'), 'Inicjator')}
|
||||
${multi('data-f="n_users"', userPairs(people), people)}</div>
|
||||
${box('self', s.initiator_may_approve, 'Inicjator może zatwierdzać')}
|
||||
${box('self', s.initiator_may_approve, 'Inicjator może zatwierdzać', forRun && !s.initiator_may_approve)}
|
||||
</details>`;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user