feat: import Galena's old approval runs and templates as history

Atrium#53 makes this module the one approval engine. Galena drains its own
engine and exports templates and finished runs (Alpaq92/Galena#14,
`python -m app.export_workflows`); this reads that file.

- python -m app.import_galena_runs runs.json [--commit]: a dry run by
  default, one transaction with --commit, idempotent (every id is a uuid5 of
  Galena's), so a later export adds only what is missing.
- Templates keep their stages and keys (quorum "one") and get this module's
  rejection rules (DEFAULT_SETTINGS); one naming a removed person is skipped.
- Runs keep state, stages, people, times and timeline; their settings say
  `end` for rejection, the rule they actually ran under. Each is on the
  DocumentRef Galena pinned (the project's main file). Unpinned, unfinished
  or with a removed person: reported, never written.
- History, not activity: no workflow.* event, no notification; one audit row
  per imported run or template, actor NULL.

Not run here: no Python on this machine and CI is not running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 23:15:30 +01:00
co-authored by Claude Opus 5.5
parent 4adfacaa7e
commit 656da736ef
4 changed files with 403 additions and 0 deletions
+2
View File
@@ -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, Atrium#53)
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
+69
View File
@@ -0,0 +1,69 @@
"""One-shot import of Galena's own approval runs and templates (Atrium#53: one approval engine).
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. 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.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
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())
+188
View File
@@ -0,0 +1,188 @@
"""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) — the decision of Atrium#53, 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.
* **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 datetime as dt
import re
import uuid
from typing import Any
from dredd_core import workflow_contract
from dredd_core.document_ref import DocumentRef
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}
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
class Report:
def __init__(self) -> None:
self.templates = self.runs = self.already = 0
self.skipped: list[str] = []
def _people(db: DbSession, ids: set[str]) -> set[str]:
if not ids:
return set()
found = db.scalars(select(AppUser.id).where(AppUser.id.in_([uuid.UUID(i) for i in ids])))
return {str(i) for i in found}
def _template(db: DbSession, t: dict[str, Any], report: Report) -> None:
tid = new_id("template", t["id"])
if db.get(WorkflowTemplate, tid) is not None:
report.already += 1
return
try:
stages = stages_of(t["stages"])
name = rules.name(t["name"], "A template's name")
except AppError as exc:
report.skipped.append(f"template {t['id']} ({t.get('name')}): {exc}")
return
named = {u for s in stages if s["approver"]["kind"] == "users" for u in s["approver"]["user_ids"]}
if named - _people(db, named):
report.skipped.append(f"template {t['id']} ({name}): 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")))
db.add(template)
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], template_ids: set[uuid.UUID], report: Report) -> None:
rid = new_id("run", r["id"])
if db.get(WorkflowRun, rid) is not None:
report.already += 1
return
label = f"run {r['id']} (document {r['node_id']})"
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 []
people = {r["started_by"], *(e["actor_id"] for e in events)}
if people - _people(db, people):
report.skipped.append(f"{label}: a person in its timeline no longer exists")
return
try:
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"):
scan = {"module": "galena", "document_id": s["document_id"], "path": r["scan"]["path"],
"commit_sha": r["scan"]["commit_sha"], "sha256": r["scan"]["sha256"]}
except (AppError, KeyError, TypeError, ValueError) as exc:
report.skipped.append(f"{label}: {exc}")
return
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 template_ids 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=r["state"], 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)
db.add(run)
db.flush() # the run before its timeline: no relationship() orders the INSERTs
for e in events:
kind = _KINDS.get(e["kind"])
if kind is None:
raise ValidationError(f"{label}: unknown event kind {e['kind']!r}.")
db.add(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"])))
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()
for t in data.get("templates") or []:
_template(db, t, report)
db.flush()
template_ids = set(db.scalars(select(WorkflowTemplate.id)))
for r in data.get("runs") or []:
_run(db, r, template_ids, report)
return report
+144
View File
@@ -0,0 +1,144 @@
"""Importing Galena's approval runs as history (Atrium#53): 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 = []
def get(self, _model, key):
return object() if key in self.existing else None
def scalars(self, stmt):
if "app_user" in str(stmt):
return list(self.people)
return [o.id for o in self.added if isinstance(o, WorkflowTemplate)]
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