feat: the contract archive in Galena (Atrium#53 step 6)

Versioned packages per contract card (card snapshot + the modules' evidence
over GET /evidence, sha256-verified; Galena-stored items read locally at
their commit), manifest + fingerprint, append-only tables (revision 0015),
automatic archiving after document.signed / workflow.signed_on_paper with
ARCHIVE_READER_TOKEN and a "Do zarchiwizowania" retry list, manual archiving
by a moderator, retention from the live card per contract type, legal holds,
two-moderator disposal with a permanent protocol, ZIP export sealed by
Parafa, 409 archived_contract on deleting an archived project, and the
console screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 13:22:56 +01:00
co-authored by Claude Opus 5.5
parent 781c2a0683
commit a3c2cef583
21 changed files with 2015 additions and 11 deletions
+11
View File
@@ -147,6 +147,17 @@ BOOTSTRAP_ADMIN_PASSWORD=change_me_admin
# keeps the latest accepted analysis. With a role prefix, use the prefixed name.
# ANALYSIS_EVENT_ROLES=arbiter_app
# The contract archive (Archiwum, spec 2026-11-25 part B): the modules' public base URLs for the
# evidence a package collects (empty = noted as not configured), the hub's read-only technical
# account's token for archiving after a signature and for Parafa's manifest seal (a secret; empty =
# signed cards wait on "Do zarchiwizowania"), and the card field naming the contract type.
# PARAFA_BASE_URL=
# WORKFLOW_BASE_URL=
# AGORA_BASE_URL=
# ARBITER_BASE_URL=
# ARCHIVE_READER_TOKEN=
# ARCHIVE_TYPE_FIELD=typ_umowy
# ── Encryption (optional) ──
# Base64 of 32 random bytes — wraps per-item data keys (server-managed mode). Empty disables
# encryption features. Generate one with:
+24
View File
@@ -82,6 +82,10 @@ backend/alembic/ env + 0001_initial (pgcrypto, enums, create_all from metadata
+ 0013_card_accepted_analysis (`document_card.accepted_analysis` jsonb, ADD COLUMN IF
NOT EXISTS: the latest analysis accepted in Arbiter, from its `analysis.accepted`,
trusted from ANALYSIS_EVENT_ROLES; the card's status does not move)
+ 0015_contract_archive (the Archive: `archive_package` / `archive_file` /
`archive_disposal_request` / `archive_disposal` APPEND-ONLY, `archive_hold` NO-DELETE,
`archive_retention` + `archive_pending` ordinary; CREATE ... IF NOT EXISTS from the
models, runtime grants from 0014's lists)
(NOTE: alembic lives at backend/alembic/, NOT under backend/app/)
**Every revision after 0001 must be idempotent** (IF [NOT] EXISTS / catalog checks):
0001 builds from the live metadata, so a fresh DB already has the current shape. And
@@ -571,6 +575,26 @@ cd frontend/editor && npm run build # rebuild the editor bundle (commit ..
UI words: **approval workflow**, **workflow template**, **stage**, **Waiting for me** / **In
progress** (PL: Obiegi akceptacji, Szablony obiegów, Etap, Czeka na mnie, W toku).
- **The contract archive („Archiwum” / „Rejestr umów”, spec 2026-11-25 part B; `services/archive*`,
`routers/archive.py`, revision 0015).** Part of Galena, not a module. One package per card,
VERSIONED (a correction is a new version; the old stays): `karta.json` (the card, its
counterparties, number, the document's main commit) + the other modules' evidence over the FIXED
contract `GET <module>/api/v1/evidence?document_id=` (`archive_collect`, sha256 checked on every
download) + by hand a scan and notes. Missing components are manifest notes. The manifest is
canonical JSON stored as the exact bytes; its sha256 is the fingerprint and the export's
`manifest.json` (Parafa's `POST /seal` adds `manifest.json.p7s`; unsealed exports carry
`NIEPODPISANY.txt`). Bytes live under DATA_DIR/archive, never in the git repositories; rows are
append-only by grant, and the only removal is disposal (bytes go, rows + protocol stay), approved by
a second moderator, refused under a legal hold (card or counterparty) or before the due date.
Retention is computed on read from the LIVE card: `ends_on` + the limitation and retention years a
moderator set for the card's contract type (the custom field `ARCHIVE_TYPE_FIELD`); no defaults,
so without them nothing is overdue. `document.signed` / `workflow.signed_on_paper` put the card on
`archive_pending` and the receiver loop makes the package with `ARCHIVE_READER_TOKEN` (strict: an
unreachable module or a bad hash leaves it on „Do zarchiwizowania”). `nodes.delete` refuses a node
with a package under it: 409 `archived_contract`. Refusal order in `archive_rules`: 404 -> 409 ->
403 -> 422. Evidence tables carry no foreign key on `node` (they outlive it); every person column
is in `0007`'s `_PERSON_COLUMNS`.
## Gotchas
- **GitPython needs the `git` binary** (in the Dockerfile; verify locally with `git --version`).
@@ -182,6 +182,15 @@ _PERSON_COLUMNS: tuple[tuple[str, str, str], ...] = (
# platform install builds the local copies in `0001`; `0014` drops them once they are empty.
("counterparty", "created_by", ""),
("counterparty_contact", "created_by", ""),
# The contract archive (revision 0015): who made a package, asked for or approved a disposal,
# set or lifted a hold, set a retention period.
("archive_package", "created_by", ""),
("archive_disposal_request", "requested_by", ""),
("archive_disposal", "requested_by", ""),
("archive_disposal", "approved_by", ""),
("archive_hold", "set_by", ""),
("archive_hold", "lifted_by", ""),
("archive_retention", "updated_by", ""),
)
#: Person ids PostgreSQL cannot see at all: a workflow stage approved by named people keeps their
@@ -200,7 +209,9 @@ _STAGE_PERSON_COLUMNS: tuple[tuple[str, str], ...] = (
#: shared store. A fresh install builds them in `0001` (from the metadata), so there they are moved
#: here like every other table.
_LATER_TABLES = frozenset({"document_meta", "table_view", "workflow_template", "document_workflow",
"workflow_event", "counterparty", "counterparty_contact"})
"workflow_event", "counterparty", "counterparty_contact",
"archive_package", "archive_disposal_request", "archive_disposal",
"archive_hold", "archive_retention"})
def _if_table(table: str, statement: str) -> str:
@@ -0,0 +1,69 @@
"""The contract archive („Archiwum”, spec 2026-11-25 part B, Atrium#53 step 6).
Seven tables from the models (`models/archive.py`), each `CREATE ... IF NOT EXISTS` (a fresh
database already has them: `0001` builds from the metadata). Then the runtime grants again, from
`0014`'s lists: the package, its files, the disposal requests and the protocols are APPEND-ONLY (the
runtime role holds no UPDATE or DELETE on them - immutability is the database's), a legal hold is
NO-DELETE (it is lifted, never removed). `archive_retention` and `archive_pending` are ordinary.
Standalone `counterparty` stays NO-DELETE, as `0014` left it.
"""
from __future__ import annotations
from dredd_core.schema import runtime_grants_sql
from sqlalchemy.schema import CreateIndex, CreateTable
from alembic import op
from app.config import get_settings
from app.models import (
ArchiveDisposal, ArchiveDisposalRequest, ArchiveFile, ArchiveHold, ArchivePackage,
ArchivePending, ArchiveRetention,
)
revision = "0015"
down_revision = "0014"
branch_labels = None
depends_on = None
#: Parents first.
MODELS = (ArchivePackage, ArchiveFile, ArchiveDisposalRequest, ArchiveDisposal, ArchiveHold,
ArchiveRetention, ArchivePending)
EVIDENCE = ("archive_package", "archive_file", "archive_disposal_request", "archive_disposal")
#: `0014`'s lists, plus the archive.
APPEND_ONLY = ("audit_log", "module_event", "module_event_receipt", "workflow_event", *EVIDENCE)
NO_DELETE: tuple[str, ...] = ("document_workflow", "workflow_template", "archive_hold")
READ_ONLY = ("alembic_version",)
def _grants(settings) -> None:
no_delete = NO_DELETE if settings.shares_identity else (*NO_DELETE, "counterparty")
op.execute(runtime_grants_sql(settings.db_app_role, append_only=APPEND_ONLY,
no_delete=no_delete, read_only=READ_ONLY))
def upgrade() -> None:
for model in MODELS:
table = model.__table__
op.execute(CreateTable(table, if_not_exists=True))
for index in sorted(table.indexes, key=lambda i: i.name):
op.execute(CreateIndex(index, if_not_exists=True))
_grants(get_settings())
def downgrade() -> None:
"""Refused while any package exists: those rows are the evidence the archive exists for."""
from sqlalchemy import text
bind = op.get_bind()
exists = bind.execute(text(
"SELECT to_regclass('archive_package') IS NOT NULL")).scalar()
if exists and bind.execute(text("SELECT EXISTS (SELECT 1 FROM archive_package)")).scalar():
raise RuntimeError("archive_package holds rows: refusing to drop the contract archive.")
for model in reversed(MODELS):
op.execute(f'DROP TABLE IF EXISTS "{model.__tablename__}"')
settings = get_settings()
no_delete = ("document_workflow", "workflow_template")
if not settings.shares_identity:
no_delete = (*no_delete, "counterparty")
op.execute(runtime_grants_sql(
settings.db_app_role, append_only=("audit_log", "module_event", "module_event_receipt",
"workflow_event"),
no_delete=no_delete, read_only=READ_ONLY))
+15
View File
@@ -164,6 +164,21 @@ class Settings(BaseSettings):
# Arbiter's `analysis.accepted` (a lawyer accepted an analysis of a document): the card keeps it.
analysis_event_roles: str = "arbiter_app"
# The contract archive (spec 2026-11-25 part B). The public base URLs of the modules whose
# evidence a package collects (`GET <url>/api/v1/evidence`); empty = not part of this
# deployment, and the manifest notes it. Parafa's also seals the export's manifest.
parafa_base_url: str = ""
workflow_base_url: str = ""
agora_base_url: str = ""
arbiter_base_url: str = ""
# The hub's read-only technical account for archiving after a signature (no person's token is
# at hand then) and for Parafa's seal. A deployment secret; empty = automatic archiving waits on
# "Do zarchiwizowania" and exports go unsealed.
archive_reader_token: str = ""
# The card's custom field (dredd-core custom fields, entity `document`) that names the contract
# type the retention periods are set for. A card without it has no retention due date.
archive_type_field: str = "typ_umowy"
# Backups (optional auto-backup of files + database; OFF by default, configured in
# Administration). Local archives live under data_dir/backups. The S3 target needs the optional
# `boto3` extra + standard AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY in the environment; the
+11
View File
@@ -31,6 +31,10 @@ from dredd_core.counterparties import Counterparty, CounterpartyAlias, Counterpa
# this app's own.
from dredd_core.events import EventCursor, EventReceipt, ModuleEvent
from dredd_core.table_views import TableView
from .archive import (
ArchiveDisposal, ArchiveDisposalRequest, ArchiveFile, ArchiveHold, ArchivePackage, ArchivePending,
ArchiveRetention,
)
from .document import DocumentCard, DocumentCardCounterparty, DocumentMeta, DocumentType
from .draft import Draft, DraftMessage
from .filecrypto import FileCrypto
@@ -76,4 +80,11 @@ __all__ = [
"WorkflowTemplate",
"DocumentWorkflow",
"WorkflowEvent",
"ArchivePackage",
"ArchiveFile",
"ArchiveDisposalRequest",
"ArchiveDisposal",
"ArchiveHold",
"ArchiveRetention",
"ArchivePending",
]
+132
View File
@@ -0,0 +1,132 @@
"""The contract archive („Archiwum”, spec 2026-11-25 part B; revision 0015).
Evidence outlives the document, so nothing here has a foreign key on `node` or `document_card`
(like `document_workflow.node_id` and `audit_log.entity_id`) - and a project whose card has a
package cannot be deleted anyway (409 `archived_contract`).
* `archive_package` - one VERSION of a card's package (a correction is a new version, the old one
stays): the manifest exactly as fingerprinted, and its sha256. APPEND-ONLY.
* `archive_file` - one stored file of a package (bytes under DATA_DIR/archive, apart from the git
repositories). APPEND-ONLY: disposal removes the bytes, never the row.
* `archive_disposal_request` / `archive_disposal` - the first moderator's request and the second
one's approval, which is the protocol: what (the fingerprints), when, who, the basis. APPEND-ONLY;
a request is open while no protocol names it.
* `archive_hold` - a legal hold on a card or a counterparty; lifted, never deleted (NO-DELETE).
* `archive_retention` - per contract type: limitation and retention periods, in years.
* `archive_pending` - „Do zarchiwizowania”: a signed card whose automatic archiving has not
happened; the row goes when a package is made.
"""
from __future__ import annotations
import datetime as dt
import uuid
from typing import Any
from sqlalchemy import (
BigInteger, DateTime, ForeignKey, Index, Integer, Text, UniqueConstraint, text,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from dredd_core import Base, UUIDPkMixin
def _now():
return mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
class ArchivePackage(UUIDPkMixin, Base):
__tablename__ = "archive_package"
node_id: Mapped[uuid.UUID] = mapped_column(nullable=False)
card_id: Mapped[uuid.UUID] = mapped_column(nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False)
trigger: Mapped[str] = mapped_column(Text, nullable=False) # auto | manual
manifest: Mapped[str] = mapped_column(Text, nullable=False) # the exact fingerprinted bytes
fingerprint: Mapped[str] = mapped_column(Text, nullable=False)
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
created_at: Mapped[dt.datetime] = _now()
__table_args__ = (UniqueConstraint("node_id", "version", name="uq_archive_package_version"),)
class ArchiveFile(UUIDPkMixin, Base):
__tablename__ = "archive_file"
package_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("archive_package.id", ondelete="RESTRICT"), nullable=False)
path: Mapped[str] = mapped_column(Text, nullable=False) # inside the ZIP: pliki/NN-name
name: Mapped[str] = mapped_column(Text, nullable=False)
kind: Mapped[str] = mapped_column(Text, nullable=False)
sha256: Mapped[str] = mapped_column(Text, nullable=False)
size: Mapped[int] = mapped_column(BigInteger, nullable=False)
source_module: Mapped[str] = mapped_column(Text, nullable=False)
source_id: Mapped[str | None] = mapped_column(Text)
commit_sha: Mapped[str | None] = mapped_column(Text)
created_at: Mapped[dt.datetime] = _now()
__table_args__ = (Index("ix_archive_file_package", "package_id"),)
class ArchiveDisposalRequest(UUIDPkMixin, Base):
__tablename__ = "archive_disposal_request"
node_id: Mapped[uuid.UUID] = mapped_column(nullable=False, index=True)
requested_by: Mapped[uuid.UUID] = mapped_column(ForeignKey("app_user.id"), nullable=False)
basis: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[dt.datetime] = _now()
class ArchiveDisposal(UUIDPkMixin, Base):
"""The disposal protocol, kept for ever."""
__tablename__ = "archive_disposal"
request_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("archive_disposal_request.id", ondelete="RESTRICT"), nullable=False, unique=True)
node_id: Mapped[uuid.UUID] = mapped_column(nullable=False, unique=True)
card_number: Mapped[str] = mapped_column(Text, nullable=False)
requested_by: Mapped[uuid.UUID] = mapped_column(ForeignKey("app_user.id"), nullable=False)
approved_by: Mapped[uuid.UUID] = mapped_column(ForeignKey("app_user.id"), nullable=False)
basis: Mapped[str] = mapped_column(Text, nullable=False)
note: Mapped[str | None] = mapped_column(Text)
# [{"version", "fingerprint", "files": [{"path", "sha256"}]}]
packages: Mapped[list[dict[str, Any]]] = mapped_column(JSONB, nullable=False)
created_at: Mapped[dt.datetime] = _now()
class ArchiveHold(UUIDPkMixin, Base):
__tablename__ = "archive_hold"
target_type: Mapped[str] = mapped_column(Text, nullable=False) # card | counterparty
target_id: Mapped[uuid.UUID] = mapped_column(nullable=False)
reason: Mapped[str] = mapped_column(Text, nullable=False)
set_by: Mapped[uuid.UUID] = mapped_column(ForeignKey("app_user.id"), nullable=False)
set_at: Mapped[dt.datetime] = _now()
lifted_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
lifted_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
lift_reason: Mapped[str | None] = mapped_column(Text)
__table_args__ = (Index("ix_archive_hold_target", "target_type", "target_id"),)
class ArchiveRetention(Base):
__tablename__ = "archive_retention"
contract_type: Mapped[str] = mapped_column(Text, primary_key=True)
limitation_years: Mapped[int] = mapped_column(Integer, nullable=False)
retention_years: Mapped[int] = mapped_column(Integer, nullable=False)
updated_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
updated_at: Mapped[dt.datetime] = _now()
class ArchivePending(Base):
__tablename__ = "archive_pending"
node_id: Mapped[uuid.UUID] = mapped_column(primary_key=True)
reason: Mapped[str] = mapped_column(Text, nullable=False) # the event kind
event_id: Mapped[str | None] = mapped_column(Text)
attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0,
server_default=text("0"))
last_error: Mapped[str | None] = mapped_column(Text)
created_at: Mapped[dt.datetime] = _now()
attempted_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
+2 -2
View File
@@ -3,7 +3,7 @@ viewing & editing. Optional; layers on the core. Later slices move its services
``galena.*`` schema) into this package — for now it declares the routers it mounts."""
from __future__ import annotations
from ..routers import cards, dashboard, drafts, files, history, register, workflows
from ..routers import archive, cards, dashboard, drafts, files, history, register, workflows
from .base import Module
GALENA = Module(
@@ -12,6 +12,6 @@ GALENA = Module(
description="Git-backed documents: projects, files, versions, review, viewing & editing, "
"document types, the contract card register and approval workflows.",
routers=(files.router, history.router, drafts.router, dashboard.router, cards.router,
register.router, workflows.router),
register.router, workflows.router, archive.router),
provides=("node_kind:project",),
)
+156
View File
@@ -0,0 +1,156 @@
"""The contract archive („Archiwum”, spec 2026-11-25 part B). Every decision is
`services/archive.py`'s (reading a package: whoever may read the card, else 404); this router only
shapes requests and responses. The work lists, holds, disposal and retention settings are this
module's moderators' (`require_moderator`).
"""
from __future__ import annotations
import datetime as dt
import uuid
from fastapi import APIRouter, Depends, File, Form, Query, Request, UploadFile
from fastapi.responses import Response
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, extract_token, get_current_user, require_moderator
from ..models import AppUser
from ..schemas import ArchiveHoldIn, ArchiveReasonIn, ArchiveRetentionIn
from ..services import archive
router = APIRouter(tags=["archive"])
@router.get("/projects/{project_id}/archive")
def read_archive(project_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
out = archive.view(db, actor=user, project_id=project_id, ip=client_ip(request))
db.commit() # the `archive.viewed` audit row
return out
@router.post("/projects/{project_id}/archive")
async def archive_by_hand(project_id: uuid.UUID, request: Request,
note: str = Form(""), file: UploadFile | None = File(None),
db: Session = Depends(get_db),
user: AppUser = Depends(require_moderator)) -> dict:
uploads = []
if file is not None and file.filename:
data = await file.read(archive.MAX_UPLOAD + 1)
uploads.append((file.filename, data))
out = archive.archive_by_hand(db, actor=user, project_id=project_id,
token=extract_token(request), uploads=uploads,
note=note.strip() or None)
db.commit()
return out
@router.get("/projects/{project_id}/archive/export")
def export_archive(project_id: uuid.UUID, request: Request, version: int | None = Query(None, ge=1),
db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> Response:
name, data, sealed = archive.export(db, actor=user, project_id=project_id, version=version,
ip=client_ip(request))
db.commit()
return Response(data, media_type="application/zip", headers={
"Content-Disposition": f'attachment; filename="{name}"',
"X-Archive-Sealed": "true" if sealed else "false",
"X-Content-Type-Options": "nosniff"})
@router.get("/archive")
def list_archive(counterparty: str | None = Query(None, max_length=200),
date_from: dt.date | None = None, date_to: dt.date | None = None,
contract_type: str | None = Query(None, max_length=200),
value_min: float | None = None, value_max: float | None = None,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> list[dict]:
return archive.listing(db, actor=user, counterparty=counterparty, date_from=date_from,
date_to=date_to, contract_type_q=contract_type,
value_min=value_min, value_max=value_max)
@router.get("/archive/pending")
def list_pending(db: Session = Depends(get_db),
_: AppUser = Depends(require_moderator)) -> list[dict]:
return archive.pending_list(db)
@router.post("/archive/pending/{project_id}/retry")
def retry_pending(project_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(require_moderator)) -> dict:
out = archive.retry(db, actor=user, project_id=project_id)
db.commit()
return out
@router.get("/archive/overdue")
def list_overdue(db: Session = Depends(get_db),
user: AppUser = Depends(require_moderator)) -> list[dict]:
return archive.overdue_list(db, actor=user)
@router.get("/archive/holds")
def list_holds(include_lifted: bool = False, db: Session = Depends(get_db),
_: AppUser = Depends(require_moderator)) -> list[dict]:
return archive.holds_list(db, include_lifted=include_lifted)
@router.post("/archive/holds")
def set_hold(body: ArchiveHoldIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(require_moderator)) -> dict:
out = archive.set_hold(db, actor=user, target_type=body.target_type, target_id=body.target_id,
reason=body.reason, ip=client_ip(request))
db.commit()
return out
@router.post("/archive/holds/{hold_id}/lift")
def lift_hold(hold_id: uuid.UUID, body: ArchiveReasonIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(require_moderator)) -> dict:
out = archive.lift_hold(db, actor=user, hold_id=hold_id, reason=body.reason,
ip=client_ip(request))
db.commit()
return out
@router.get("/archive/disposals")
def list_disposals(db: Session = Depends(get_db),
_: AppUser = Depends(require_moderator)) -> dict:
return archive.disposals_list(db)
@router.post("/projects/{project_id}/archive/disposal")
def request_disposal(project_id: uuid.UUID, body: ArchiveReasonIn, request: Request,
db: Session = Depends(get_db),
user: AppUser = Depends(require_moderator)) -> dict:
out = archive.request_disposal(db, actor=user, project_id=project_id, basis=body.reason,
ip=client_ip(request))
db.commit()
return out
@router.post("/projects/{project_id}/archive/disposal/approve")
def approve_disposal(project_id: uuid.UUID, body: ArchiveReasonIn, request: Request,
db: Session = Depends(get_db),
user: AppUser = Depends(require_moderator)) -> dict:
out = archive.approve_disposal(db, actor=user, project_id=project_id, note=body.reason,
ip=client_ip(request))
db.commit()
archive.purge(out.pop("package_ids")) # the bytes go only once the protocol is committed
return out
@router.get("/archive/retention")
def list_retention(db: Session = Depends(get_db),
_: AppUser = Depends(get_current_user)) -> list[dict]:
return archive.retention_list(db)
@router.put("/archive/retention/{contract_type}")
def put_retention(contract_type: str, body: ArchiveRetentionIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(require_moderator)) -> dict:
out = archive.set_retention(db, actor=user, contract_type_code=contract_type,
limitation_years=body.limitation_years,
retention_years=body.retention_years, ip=client_ip(request))
db.commit()
return out
+24 -1
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import re
import uuid
from typing import Annotated
from typing import Annotated, Literal
from pydantic import AfterValidator, BaseModel, Field
@@ -321,3 +321,26 @@ MAX_ROLE_IDS = 200
class ProjectRolesIn(BaseModel):
project_ids: list[uuid.UUID] = Field(min_length=1, max_length=MAX_ROLE_IDS)
# ── the contract archive (spec 2026-11-25 part B) ────────────────────────────
class ArchiveReasonIn(BaseModel):
"""A basis or a reason; required where the rule says so (checked by `archive_rules`)."""
model_config = {"extra": "forbid"}
reason: str | None = Field(default=None, max_length=2000)
class ArchiveHoldIn(BaseModel):
model_config = {"extra": "forbid"}
target_type: Literal["card", "counterparty"]
target_id: uuid.UUID
reason: str = Field(max_length=2000)
class ArchiveRetentionIn(BaseModel):
model_config = {"extra": "forbid"}
limitation_years: int = Field(ge=0, le=100)
retention_years: int = Field(ge=0, le=100)
+652
View File
@@ -0,0 +1,652 @@
"""The contract archive („Archiwum” / „Rejestr umów”, spec 2026-11-25 part B, Atrium#53 step 6):
packages, retention, legal holds, two-person disposal, export, the refusal to delete.
Pure rules are `archive_rules`, the calls to the other modules `archive_collect`; this module owns
the database and the stored bytes.
* **Package** = one card, versioned: the card's local snapshot (`karta.json`: fields,
counterparties, number, the document's main commit), the modules' evidence, and - by hand - a
scan with notes. Bytes live under DATA_DIR/archive/<package>/<file>, apart from the git
repositories. Rows are append-only (revision 0015's grants).
* **Access.** Reading a package: whoever may read the card's project (moderators resolve there as
managers) - else 404. Everything else (archiving by hand, holds, disposal, retention, the work
lists) is for this module's moderators; the router guards it with `deps.require_moderator`.
* **Audit** through `dredd_core.audit.record`: `archive.created`, `.viewed`, `.exported`,
`.hold_set`, `.hold_lifted`, `.disposal_requested`, `.disposed`, `.retention_set`.
"""
from __future__ import annotations
import datetime as dt
import io
import json
import logging
import shutil
import uuid
import zipfile
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any
from sqlalchemy import func, select
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..enums import NodeKind
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import (
AppUser, ArchiveDisposal, ArchiveDisposalRequest, ArchiveFile, ArchiveHold, ArchivePackage,
ArchivePending, ArchiveRetention, Counterparty, DocumentCard, DocumentCardCounterparty, Node,
)
from . import archive_collect as collector
from . import archive_rules as rules
from . import audit, authz, moderation
log = logging.getLogger("galena.archive")
MAX_UPLOAD = 64 * 1024 * 1024
MAX_NOTE = 2000
HOLD_TARGETS = ("card", "counterparty")
_UTC = dt.timezone.utc
# ── storage, apart from the git repositories ─────────────────────────────────
def _root() -> Path:
return Path(get_settings().data_dir) / "archive"
def _blob(package_id: uuid.UUID, file_id: uuid.UUID) -> Path:
return _root() / str(package_id) / str(file_id)
def _store(package_id: uuid.UUID, file_id: uuid.UUID, data: bytes) -> None:
path = _blob(package_id, file_id)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".part")
tmp.write_bytes(data)
tmp.replace(path)
# ── reads ─────────────────────────────────────────────────────────────────────
def _card(db: DbSession, node_id: uuid.UUID) -> DocumentCard | None:
return db.scalar(select(DocumentCard).where(DocumentCard.node_id == node_id))
def _readable(db: DbSession, actor: AppUser, project_id: uuid.UUID) -> tuple[Node, DocumentCard]:
"""The project and its card for whoever may read it, or a moderator; otherwise 404."""
node = db.get(Node, project_id)
if node is None or node.kind != NodeKind.project:
raise NotFoundError("Not found.")
if not moderation.is_moderator(db, actor):
authz.assert_can_read(db, actor, node)
card = _card(db, node.id)
if card is None:
raise NotFoundError("Not found.")
return node, card
def packages_of(db: DbSession, node_id: uuid.UUID) -> list[ArchivePackage]:
return list(db.scalars(select(ArchivePackage).where(ArchivePackage.node_id == node_id)
.order_by(ArchivePackage.version)).all())
def _files(db: DbSession, package_ids: list[uuid.UUID]) -> dict[uuid.UUID, list[ArchiveFile]]:
out: dict[uuid.UUID, list[ArchiveFile]] = {i: [] for i in package_ids}
if package_ids:
for f in db.scalars(select(ArchiveFile).where(ArchiveFile.package_id.in_(package_ids))
.order_by(ArchiveFile.path)):
out[f.package_id].append(f)
return out
def _protocol(db: DbSession, node_id: uuid.UUID) -> ArchiveDisposal | None:
return db.scalar(select(ArchiveDisposal).where(ArchiveDisposal.node_id == node_id))
def _open_request(db: DbSession, node_id: uuid.UUID) -> ArchiveDisposalRequest | None:
done = select(ArchiveDisposal.request_id)
return db.scalar(select(ArchiveDisposalRequest)
.where(ArchiveDisposalRequest.node_id == node_id,
ArchiveDisposalRequest.id.not_in(done))
.order_by(ArchiveDisposalRequest.created_at.desc()).limit(1))
def contract_type(card: DocumentCard) -> str | None:
value = (card.custom_fields or {}).get(get_settings().archive_type_field)
return str(value).strip() or None if value not in (None, "") else None
def retention_rules(db: DbSession) -> dict[str, tuple[int, int]]:
return {r.contract_type: (r.limitation_years, r.retention_years)
for r in db.scalars(select(ArchiveRetention))}
def due_of(card: DocumentCard, rules_by_type: dict[str, tuple[int, int]]) -> dt.date | None:
"""From the LIVE card: an annex that moves the end date moves this too."""
kind = contract_type(card)
return rules.due_date(card.ends_on, rules_by_type.get(kind) if kind else None)
def _counterparty_ids(db: DbSession, card_id: uuid.UUID) -> list[uuid.UUID]:
return list(db.scalars(select(DocumentCardCounterparty.counterparty_id)
.where(DocumentCardCounterparty.card_id == card_id)))
def active_holds(db: DbSession, node_id: uuid.UUID, card: DocumentCard) -> list[ArchiveHold]:
cps = _counterparty_ids(db, card.id)
on = (ArchiveHold.target_type == "card") & (ArchiveHold.target_id == node_id)
if cps:
on = on | ((ArchiveHold.target_type == "counterparty") & ArchiveHold.target_id.in_(cps))
q = select(ArchiveHold).where(ArchiveHold.lifted_at.is_(None), on)
return list(db.scalars(q.order_by(ArchiveHold.set_at)))
def _state(db: DbSession, node_id: uuid.UUID, card: DocumentCard,
today: dt.date) -> rules.DisposalState:
request = _open_request(db, node_id)
return rules.DisposalState(
has_package=bool(packages_of(db, node_id)),
disposed=_protocol(db, node_id) is not None,
held=bool(active_holds(db, node_id, card)),
overdue=rules.is_overdue(due_of(card, retention_rules(db)), today),
open_request_by=str(request.requested_by) if request else None)
def _package_out(p: ArchivePackage, files: list[ArchiveFile], disposed: bool) -> dict:
manifest = json.loads(p.manifest)
return {"id": str(p.id), "version": p.version, "trigger": p.trigger,
"fingerprint": p.fingerprint, "created_at": p.created_at.isoformat(),
"created_by": str(p.created_by) if p.created_by else None,
"notes": manifest.get("notes", []), "disposed": disposed,
"files": [{"path": f.path, "name": f.name, "kind": f.kind, "sha256": f.sha256,
"size": f.size, "source_module": f.source_module, "source_id": f.source_id,
"commit_sha": f.commit_sha} for f in files]}
def _hold_out(h: ArchiveHold) -> dict:
return {"id": str(h.id), "target_type": h.target_type, "target_id": str(h.target_id),
"reason": h.reason, "set_by": str(h.set_by), "set_at": h.set_at.isoformat(),
"lifted_by": str(h.lifted_by) if h.lifted_by else None,
"lifted_at": h.lifted_at.isoformat() if h.lifted_at else None,
"lift_reason": h.lift_reason}
def _protocol_out(p: ArchiveDisposal) -> dict:
return {"id": str(p.id), "project_id": str(p.node_id), "card_number": p.card_number,
"requested_by": str(p.requested_by), "approved_by": str(p.approved_by),
"basis": p.basis, "note": p.note, "packages": p.packages,
"created_at": p.created_at.isoformat()}
def view(db: DbSession, *, actor: AppUser, project_id: uuid.UUID, ip: str | None = None,
today: dt.date | None = None) -> dict:
"""The card's archive: every package version, holds, the due date, the disposal. Audited as
`archive.viewed` when there is a package to see. No commit."""
today = today or dt.date.today()
node, card = _readable(db, actor, project_id)
packages = packages_of(db, node.id)
protocol = _protocol(db, node.id)
files = _files(db, [p.id for p in packages])
due = due_of(card, retention_rules(db))
request = _open_request(db, node.id)
pending = db.get(ArchivePending, node.id)
if packages:
audit.record(db, actor_id=actor.id, action="archive.viewed", entity_type="project",
entity_id=node.id, ip=ip)
return {"project_id": str(node.id), "card_number": card.number,
"packages": [_package_out(p, files[p.id], protocol is not None) for p in packages],
"contract_type": contract_type(card), "ends_on": card.ends_on.isoformat() if card.ends_on else None,
"due_on": due.isoformat() if due else None, "overdue": rules.is_overdue(due, today),
"holds": [_hold_out(h) for h in active_holds(db, node.id, card)],
"disposal_request": ({"id": str(request.id), "requested_by": str(request.requested_by),
"basis": request.basis, "created_at": request.created_at.isoformat()}
if request else None),
"disposal": _protocol_out(protocol) if protocol else None,
"pending": ({"reason": pending.reason, "attempts": pending.attempts,
"last_error": pending.last_error} if pending else None),
"can_moderate": moderation.is_moderator(db, actor)}
# ── making a package ──────────────────────────────────────────────────────────
def _snapshot(db: DbSession, node: Node, card: DocumentCard) -> tuple[bytes, str | None, list[str]]:
from . import cards, git_facade
notes: list[str] = []
try:
commit = git_facade.resolve_commit(node.id)
except Exception: # noqa: BLE001 - an empty or missing repository: noted, not fatal
commit = None
notes.append("galena: the document has no main version - no commit recorded")
out = cards.card_out(db, None, card, node) # type: ignore[arg-type] - actor unused w/o detail
out["document_commit"] = commit
return rules.canonical(out), commit, notes
def _local_copy(project_id: uuid.UUID):
"""An item whose bytes live in Galena: the file of this document's repository at `commit`
whose sha256 is `expected`, or None (then the module's `download` is tried)."""
from . import git_facade
def read(commit: str, expected: str) -> bytes | None:
if not rules.is_sha256(expected) or not commit.isalnum():
return None
for _path, _size, data in git_facade.scan_blobs(project_id, ref=commit, limit=5000):
blob = data()
if rules.sha256(blob) == expected:
return blob
return None
return read
def make_package(db: DbSession, *, node: Node, card: DocumentCard, actor_id: uuid.UUID | None,
trigger: str, token: str | None, strict: bool,
uploads: list[tuple[str, bytes]] = (), note: str | None = None,
modules: dict | None = None) -> ArchivePackage:
"""Collect and store one new version. `strict` (automatic) raises `CollectFailed` before
anything is written. No commit."""
if _protocol(db, node.id) is not None:
raise ConflictError("This contract's package was disposed of.", {"code": "already_disposed"})
got = collector.collect(str(node.id), token=token,
modules=collector.clients() if modules is None else modules,
strict=strict, local=_local_copy(node.id))
snapshot, commit, notes = _snapshot(db, node, card)
entries = [{"name": "karta.json", "kind": "card_snapshot", "data": snapshot,
"sha256": rules.sha256(snapshot),
"source": {"module": "galena", "id": str(card.id), "commit": commit}}]
entries += got.files
for name, data in uploads:
entries.append({"name": name, "kind": "upload", "data": data, "sha256": rules.sha256(data),
"source": {"module": "galena", "id": None, "commit": None}})
notes += got.notes
if note:
notes.append(f"galena: {note[:MAX_NOTE]}")
db.execute(select(DocumentCard.id).where(DocumentCard.id == card.id).with_for_update())
version = (db.scalar(select(func.max(ArchivePackage.version))
.where(ArchivePackage.node_id == node.id)) or 0) + 1
package_id = uuid.uuid4()
now = dt.datetime.now(_UTC)
rows, listed = [], []
for index, e in enumerate(entries, start=1):
path = f"{rules.FILES_DIR}/{rules.safe_name(e['name'], index)}"
file_id = uuid.uuid4()
_store(package_id, file_id, e["data"])
src = e["source"]
rows.append(ArchiveFile(id=file_id, package_id=package_id, path=path, name=e["name"],
kind=e["kind"], sha256=e["sha256"], size=len(e["data"]),
source_module=src["module"], source_id=src["id"],
commit_sha=src["commit"]))
listed.append({"path": path, "name": e["name"], "kind": e["kind"], "sha256": e["sha256"],
"size": len(e["data"]), "source": src})
manifest = rules.build_manifest(
document_id=str(node.id), card_id=str(card.id), card_number=card.number, version=version,
created_at=now.isoformat(), created_by=str(actor_id) if actor_id else None,
trigger=trigger, files=listed, notes=notes)
data, fingerprint = rules.fingerprint(manifest)
package = ArchivePackage(id=package_id, node_id=node.id, card_id=card.id, version=version,
trigger=trigger, manifest=data.decode("utf-8"),
fingerprint=fingerprint, created_by=actor_id, created_at=now)
db.add(package)
db.flush()
db.add_all(rows)
pending = db.get(ArchivePending, node.id)
if pending is not None:
db.delete(pending)
db.flush()
audit.record(db, actor_id=actor_id, action="archive.created", entity_type="project",
entity_id=node.id, detail=f"v{version} {trigger}",
diff={"fingerprint": [None, fingerprint]})
return package
def archive_by_hand(db: DbSession, *, actor: AppUser, project_id: uuid.UUID, token: str | None,
uploads: list[tuple[str, bytes]], note: str | None) -> dict:
"""A moderator archives any card - also an old paper contract (a scan + notes) - collecting
with their own token; missing components become notes. No commit."""
node, card = _readable(db, actor, project_id)
if note is not None and len(note) > MAX_NOTE:
raise ValidationError("The note is too long.", {"code": "note_too_long"})
for name, data in uploads:
if len(data) > MAX_UPLOAD:
raise ValidationError("The file is too large.", {"code": "file_too_large"})
package = make_package(db, node=node, card=card, actor_id=actor.id, trigger="manual",
token=token, strict=False, uploads=uploads, note=note or None)
return {"version": package.version, "fingerprint": package.fingerprint}
# ── automatic, after a signature ─────────────────────────────────────────────
def enqueue(db: DbSession, *, node_id: uuid.UUID, reason: str, event_id: str | None) -> None:
"""A signed card goes on the work list; `process_pending` makes its package. No commit."""
if _card(db, node_id) is None or db.get(ArchivePending, node_id) is not None:
return
db.add(ArchivePending(node_id=node_id, reason=reason, event_id=event_id, attempts=0))
db.flush()
def _attempt(db: DbSession, pending: ArchivePending, modules: dict | None = None) -> bool:
node = db.get(Node, pending.node_id)
card = _card(db, pending.node_id)
pending.attempts += 1
pending.attempted_at = dt.datetime.now(_UTC)
if node is None or card is None:
pending.last_error = "the document or its card is gone"
return False
token = get_settings().archive_reader_token
if not token:
pending.last_error = "ARCHIVE_READER_TOKEN is not set"
return False
try:
make_package(db, node=node, card=card, actor_id=None, trigger="auto", token=token,
strict=True, modules=modules)
except collector.CollectFailed as exc:
pending.last_error = str(exc)[:500]
return False
except ConflictError as exc:
pending.last_error = str(exc)[:500]
return False
return True
def process_pending(db: DbSession, *, modules: dict | None = None, limit: int = 20) -> int:
"""One automatic attempt for each card that has had none. A failure stays on the list for a
moderator (`retry` or archiving by hand). No commit."""
done = 0
for pending in list(db.scalars(select(ArchivePending).where(ArchivePending.attempts == 0)
.order_by(ArchivePending.created_at).limit(limit))):
done += _attempt(db, pending, modules)
return done
def retry(db: DbSession, *, actor: AppUser, project_id: uuid.UUID) -> dict:
pending = db.get(ArchivePending, project_id)
if pending is None:
raise NotFoundError("Not found.")
ok = _attempt(db, pending)
db.flush()
return {"archived": ok, "last_error": None if ok else pending.last_error}
def pending_list(db: DbSession) -> list[dict]:
rows = db.execute(select(ArchivePending, DocumentCard.number, Node.name)
.join(DocumentCard, DocumentCard.node_id == ArchivePending.node_id, isouter=True)
.join(Node, Node.id == ArchivePending.node_id, isouter=True)
.order_by(ArchivePending.created_at)).all()
return [{"project_id": str(p.node_id), "card_number": number, "name": name, "reason": p.reason,
"attempts": p.attempts, "last_error": p.last_error,
"created_at": p.created_at.isoformat()} for p, number, name in rows]
# ── the lists ─────────────────────────────────────────────────────────────────
def _latest_packages(db: DbSession) -> dict[uuid.UUID, ArchivePackage]:
out: dict[uuid.UUID, ArchivePackage] = {}
for p in db.scalars(select(ArchivePackage).order_by(ArchivePackage.node_id, ArchivePackage.version)):
out[p.node_id] = p
return out
def _decimal(value: Any, field: str) -> Decimal | None:
if value in (None, ""):
return None
try:
return Decimal(str(value))
except InvalidOperation:
raise ValidationError(f"{field} is not a number.", {"code": "value_invalid"}) from None
def listing(db: DbSession, *, actor: AppUser, counterparty: str | None = None,
date_from: dt.date | None = None, date_to: dt.date | None = None,
contract_type_q: str | None = None, value_min: Any = None, value_max: Any = None,
today: dt.date | None = None, limit: int = 200) -> list[dict]:
"""„Archiwum”: every archived card the reader may open - by counterparty (the card's text or
a linked register name), archiving date, contract type, value."""
today = today or dt.date.today()
vmin, vmax = _decimal(value_min, "value_min"), _decimal(value_max, "value_max")
latest = _latest_packages(db)
if not latest:
return []
rows = db.execute(select(DocumentCard, Node).join(Node, Node.id == DocumentCard.node_id)
.where(DocumentCard.node_id.in_(list(latest)))).all()
if not moderation.is_moderator(db, actor):
readable = authz.readable_node_ids(db, actor, [n for _, n in rows])
rows = [(c, n) for c, n in rows if n.id in readable]
names: dict[uuid.UUID, list[str]] = {}
if rows:
for card_id, name in db.execute(
select(DocumentCardCounterparty.card_id, Counterparty.name)
.join(Counterparty, Counterparty.id == DocumentCardCounterparty.counterparty_id)
.where(DocumentCardCounterparty.card_id.in_([c.id for c, _ in rows]))):
names.setdefault(card_id, []).append(name)
disposed = set(db.scalars(select(ArchiveDisposal.node_id)))
by_type = retention_rules(db)
out = []
for card, node in rows:
p = latest[node.id]
parties = [card.counterparty or "", *names.get(card.id, [])]
if counterparty and not any(counterparty.lower() in s.lower() for s in parties if s):
continue
day = p.created_at.date()
if (date_from and day < date_from) or (date_to and day > date_to):
continue
kind = contract_type(card)
if contract_type_q and (kind or "").lower() != contract_type_q.strip().lower():
continue
if vmin is not None and (card.value_amount is None or card.value_amount < vmin):
continue
if vmax is not None and (card.value_amount is None or card.value_amount > vmax):
continue
due = due_of(card, by_type)
out.append({"project_id": str(node.id), "name": node.name, "card_number": card.number,
"counterparty": ", ".join(s for s in parties if s) or None,
"contract_type": kind,
"value_amount": str(card.value_amount) if card.value_amount is not None else None,
"value_currency": card.value_currency, "version": p.version,
"fingerprint": p.fingerprint, "archived_at": p.created_at.isoformat(),
"due_on": due.isoformat() if due else None,
"overdue": rules.is_overdue(due, today) and node.id not in disposed,
"disposed": node.id in disposed})
out.sort(key=lambda r: r["archived_at"], reverse=True)
return out[:limit]
def overdue_list(db: DbSession, *, actor: AppUser, today: dt.date | None = None) -> list[dict]:
"""„Po terminie retencji”, computed on read. Nothing is disposed of automatically."""
today = today or dt.date.today()
rows = [r for r in listing(db, actor=actor, today=today, limit=10_000) if r["overdue"]]
for r in rows:
node_id = uuid.UUID(r["project_id"])
card = _card(db, node_id)
r["held"] = bool(active_holds(db, node_id, card)) if card else False
request = _open_request(db, node_id)
r["disposal_requested"] = request is not None
return rows
# ── legal holds ───────────────────────────────────────────────────────────────
def set_hold(db: DbSession, *, actor: AppUser, target_type: str, target_id: uuid.UUID,
reason: Any, ip: str | None = None) -> dict:
if target_type not in HOLD_TARGETS:
raise ValidationError("A hold is on a card or a counterparty.", {"code": "target_invalid"})
if target_type == "card":
if _card(db, target_id) is None:
raise NotFoundError("Not found.")
elif db.get(Counterparty, target_id) is None:
raise NotFoundError("Not found.")
text = rules.check_hold_reason(reason)
hold = ArchiveHold(target_type=target_type, target_id=target_id, reason=text, set_by=actor.id)
db.add(hold)
db.flush()
audit.record(db, actor_id=actor.id, action="archive.hold_set", entity_type=target_type,
entity_id=target_id, detail=text[:500], ip=ip)
return _hold_out(hold)
def lift_hold(db: DbSession, *, actor: AppUser, hold_id: uuid.UUID, reason: Any,
ip: str | None = None) -> dict:
hold = db.get(ArchiveHold, hold_id, with_for_update=True)
if hold is None:
raise NotFoundError("Not found.")
if hold.lifted_at is not None:
raise ConflictError("This hold has been lifted.", {"code": "hold_lifted"})
text = rules.check_hold_reason(reason)
hold.lifted_by, hold.lifted_at, hold.lift_reason = actor.id, dt.datetime.now(_UTC), text
db.flush()
audit.record(db, actor_id=actor.id, action="archive.hold_lifted", entity_type=hold.target_type,
entity_id=hold.target_id, detail=text[:500], ip=ip)
return _hold_out(hold)
def holds_list(db: DbSession, *, include_lifted: bool = False) -> list[dict]:
q = select(ArchiveHold).order_by(ArchiveHold.set_at.desc())
if not include_lifted:
q = q.where(ArchiveHold.lifted_at.is_(None))
holds = list(db.scalars(q))
out = []
for h in holds:
row = _hold_out(h)
if h.target_type == "card":
card, node = _card(db, h.target_id), db.get(Node, h.target_id)
row["label"] = " ".join(x for x in (card.number if card else None,
node.name if node else None) if x)
else:
cp = db.get(Counterparty, h.target_id)
row["label"] = cp.name if cp else None
out.append(row)
return out
# ── two-person disposal ───────────────────────────────────────────────────────
def request_disposal(db: DbSession, *, actor: AppUser, project_id: uuid.UUID, basis: Any,
ip: str | None = None, today: dt.date | None = None) -> dict:
node, card = _readable(db, actor, project_id)
db.execute(select(DocumentCard.id).where(DocumentCard.id == card.id).with_for_update())
text = rules.check_request(_state(db, node.id, card, today or dt.date.today()), basis)
request = ArchiveDisposalRequest(node_id=node.id, requested_by=actor.id, basis=text)
db.add(request)
db.flush()
audit.record(db, actor_id=actor.id, action="archive.disposal_requested", entity_type="project",
entity_id=node.id, detail=text[:500], ip=ip)
return {"id": str(request.id)}
def approve_disposal(db: DbSession, *, actor: AppUser, project_id: uuid.UUID, note: Any = None,
ip: str | None = None, today: dt.date | None = None) -> dict:
"""The second moderator: the files go, the protocol stays for ever. The bytes are removed
after the protocol row is flushed; a failed removal is logged and the protocol still says what
was ordered. No commit (the caller commits, then `purge` runs)."""
node, card = _readable(db, actor, project_id)
db.execute(select(DocumentCard.id).where(DocumentCard.id == card.id).with_for_update())
state = _state(db, node.id, card, today or dt.date.today())
text = rules.check_approve(state, str(actor.id), note)
request = _open_request(db, node.id)
packages = packages_of(db, node.id)
files = _files(db, [p.id for p in packages])
protocol = ArchiveDisposal(
request_id=request.id, node_id=node.id, card_number=card.number,
requested_by=request.requested_by, approved_by=actor.id, basis=request.basis, note=text,
packages=[{"version": p.version, "fingerprint": p.fingerprint,
"files": [{"path": f.path, "sha256": f.sha256} for f in files[p.id]]}
for p in packages])
db.add(protocol)
db.flush()
audit.record(db, actor_id=actor.id, action="archive.disposed", entity_type="project",
entity_id=node.id, detail=request.basis[:500], ip=ip,
diff={"fingerprints": [[p.fingerprint for p in packages], None]})
return {"protocol": _protocol_out(protocol), "package_ids": [str(p.id) for p in packages]}
def purge(package_ids: list[str]) -> None:
for pid in package_ids:
try:
shutil.rmtree(_root() / str(uuid.UUID(pid)), ignore_errors=False)
except FileNotFoundError:
pass
except OSError:
log.exception("archive: could not remove the files of package %s", pid)
def disposals_list(db: DbSession) -> dict:
done = select(ArchiveDisposal.request_id)
open_rows = db.execute(select(ArchiveDisposalRequest, DocumentCard.number, Node.name)
.join(DocumentCard, DocumentCard.node_id == ArchiveDisposalRequest.node_id, isouter=True)
.join(Node, Node.id == ArchiveDisposalRequest.node_id, isouter=True)
.where(ArchiveDisposalRequest.id.not_in(done))
.order_by(ArchiveDisposalRequest.created_at)).all()
protocols = db.scalars(select(ArchiveDisposal).order_by(ArchiveDisposal.created_at.desc()))
return {"requests": [{"id": str(r.id), "project_id": str(r.node_id), "card_number": number,
"name": name, "requested_by": str(r.requested_by), "basis": r.basis,
"created_at": r.created_at.isoformat()} for r, number, name in open_rows],
"protocols": [_protocol_out(p) for p in protocols]}
# ── retention settings ────────────────────────────────────────────────────────
def retention_list(db: DbSession) -> list[dict]:
return [{"contract_type": r.contract_type, "limitation_years": r.limitation_years,
"retention_years": r.retention_years}
for r in db.scalars(select(ArchiveRetention).order_by(ArchiveRetention.contract_type))]
def set_retention(db: DbSession, *, actor: AppUser, contract_type_code: str, limitation_years: Any,
retention_years: Any, ip: str | None = None) -> dict:
code = (contract_type_code or "").strip()
if not code or len(code) > 200:
raise ValidationError("Name the contract type.", {"code": "type_invalid"})
lim = rules.check_years(limitation_years, "limitation_years")
ret = rules.check_years(retention_years, "retention_years")
row = db.get(ArchiveRetention, code)
before = [row.limitation_years, row.retention_years] if row else None
if row is None:
row = ArchiveRetention(contract_type=code, limitation_years=lim, retention_years=ret,
updated_by=actor.id)
db.add(row)
else:
row.limitation_years, row.retention_years, row.updated_by = lim, ret, actor.id
row.updated_at = dt.datetime.now(_UTC)
db.flush()
audit.record(db, actor_id=actor.id, action="archive.retention_set", entity_type="contract_type",
detail=code[:200], ip=ip, diff={"years": [before, [lim, ret]]})
return {"contract_type": code, "limitation_years": lim, "retention_years": ret}
# ── export ────────────────────────────────────────────────────────────────────
def export(db: DbSession, *, actor: AppUser, project_id: uuid.UUID, version: int | None = None,
ip: str | None = None, seal=collector.seal) -> tuple[str, bytes, bool]:
"""ZIP: the package files, `manifest.json` (the fingerprinted bytes) and, when Parafa sealed
it, `manifest.json.p7s`. Without the seal the ZIP carries `NIEPODPISANY.txt` saying why.
Returns (file name, bytes, sealed). Audited as `archive.exported`. No commit."""
node, card = _readable(db, actor, project_id)
packages = packages_of(db, node.id)
if version is not None:
packages = [p for p in packages if p.version == version]
if not packages:
raise NotFoundError("Not found.")
package = packages[-1]
if _protocol(db, node.id) is not None:
raise ConflictError("This package was disposed of; its protocol remains.",
{"code": "already_disposed"})
manifest = package.manifest.encode("utf-8")
p7s, why = seal(manifest)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
z.writestr("manifest.json", manifest)
if p7s is not None:
z.writestr("manifest.json.p7s", p7s)
else:
z.writestr("NIEPODPISANY.txt", (why or "not sealed") + "\n")
for f in _files(db, [package.id])[package.id]:
blob = _blob(package.id, f.id)
data = blob.read_bytes() if blob.exists() else None
if data is None or rules.sha256(data) != f.sha256:
raise ConflictError("A stored file is missing or damaged.", {"code": "file_damaged"})
z.writestr(f.path, data)
audit.record(db, actor_id=actor.id, action="archive.exported", entity_type="project",
entity_id=node.id, detail=f"v{package.version}" + ("" if p7s else " unsealed"), ip=ip)
return f"{card.number}-v{package.version}.zip", buf.getvalue(), p7s is not None
# ── the refusal to delete ─────────────────────────────────────────────────────
def assert_deletable(db: DbSession, node: Node) -> None:
"""409 `archived_contract` when the node, or any project under it, has a package."""
prefix = node.path.rstrip("/") + "/"
hit = db.scalar(select(ArchivePackage.id).join(Node, Node.id == ArchivePackage.node_id)
.where((Node.id == node.id) | Node.path.startswith(prefix, autoescape=True))
.limit(1))
if hit is not None:
raise ConflictError("A contract here is archived; it cannot be deleted.",
{"code": "archived_contract"})
+188
View File
@@ -0,0 +1,188 @@
"""Collecting a contract's evidence from the other modules (spec 2026-11-25 part B), over the FIXED
contract every module implements:
GET <module>/api/v1/evidence?document_id=<uuid>
-> {"module", "document_id", "items": [{"kind", "name", "sha256", "source_id",
"commit_sha" | null, "download"}], "note" | null}
`download` is relative to that module's /api/v1/ and is fetched with the same bearer. Each file's
sha256 is checked against the item before it is kept.
* **Manual** (`strict=False`, a moderator's own token): 401/403/404, an unreachable module, a bad
item or a hash mismatch become notes in the manifest - archiving goes on with what there is.
* **Automatic** (`strict=True`, ARCHIVE_READER_TOKEN): 404 is still a note (the module has nothing
on this document), but an unreachable module, a 401/403/5xx, or a file that does not match its
hash raise `CollectFailed`, and the card waits on „Do zarchiwizowania” instead.
Two exceptions (agreed with the modules): an item whose bytes live in GALENA (a Workflow scan stored
here, an Agora round in Galena, a Parafa document in Galena) is read from Galena's own repository at
its `commit_sha` (`local`, matched by sha256) and never fetched - its `download` would call back
into Galena, where the technical account has no access. And Arbiter's `accepted_card` is kept even
when its sha256 differs (the fingerprint covers the unmasked card): recorded, with a note.
A module with no base URL configured is a note in both modes. No database here; the clients are
anything with `ModuleClient.request`'s shape, so tests pass fakes.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from collections.abc import Callable
from typing import Any, Protocol
from dredd_core.module_client import ModuleCallError, ModuleClient
from ..config import get_settings
from . import archive_rules as rules
#: Module key -> (settings attribute with its public base URL, service label).
MODULES: dict[str, tuple[str, str]] = {
"parafa": ("parafa_base_url", "Parafa"),
"workflow": ("workflow_base_url", "Workflow"),
"agora": ("agora_base_url", "Agora"),
"arbiter": ("arbiter_base_url", "Arbiter"),
}
MAX_ITEMS = 50
MAX_FILE = 64 * 1024 * 1024
SEAL_MAX = 1024 * 1024
class Client(Protocol):
def request(self, method: str, path: str, *, token: str | None, **kw: Any) -> Any: ...
class CollectFailed(RuntimeError):
"""Automatic archiving could not get a module's evidence; the card goes on the retry list."""
@dataclass
class Collected:
files: list[dict] = field(default_factory=list) # {name, kind, sha256, data, source}
notes: list[str] = field(default_factory=list)
def clients() -> dict[str, Client | None]:
settings = get_settings()
out: dict[str, Client | None] = {}
for key, (attr, label) in MODULES.items():
url = (getattr(settings, attr, "") or "").strip()
out[key] = ModuleClient(url, service=label, max_body=MAX_FILE) if url else None
return out
def _fail(strict: bool, out: Collected, note: str) -> None:
if strict:
raise CollectFailed(note)
out.notes.append(note)
#: (commit_sha, sha256) -> the bytes of Galena's own copy, or None.
Local = Callable[[str, str], "bytes | None"]
#: Kept although its sha256 differs: Arbiter's fingerprint is of the unmasked card.
LENIENT_KINDS = frozenset({"accepted_card"})
def collect(document_id: str, *, token: str | None, modules: dict[str, Client | None],
strict: bool, local: Local | None = None) -> Collected:
out = Collected()
for key in MODULES:
client = modules.get(key)
if client is None:
out.notes.append(f"{key}: not configured - nothing collected")
continue
if not token:
_fail(strict, out, f"{key}: no credential to ask with")
continue
try:
answer = client.request("GET", "/evidence", token=token,
params={"document_id": document_id})
except ModuleCallError:
_fail(strict, out, f"{key}: unreachable")
continue
if answer.status == 404:
out.notes.append(f"{key}: nothing on this document")
continue
if not answer.ok:
_fail(strict, out, f"{key}: answered {answer.status}")
continue
try:
body = answer.json()
except (ValueError, UnicodeDecodeError):
_fail(strict, out, f"{key}: not a JSON answer")
continue
if not isinstance(body, dict) or not isinstance(body.get("items", []), list):
_fail(strict, out, f"{key}: malformed answer")
continue
if body.get("note"):
out.notes.append(f"{key}: {str(body['note'])[:500]}")
items = body.get("items") or []
if not items:
out.notes.append(f"{key}: no evidence")
for item in items[:MAX_ITEMS]:
_item(key, client, token, item, out, strict, local)
if len(items) > MAX_ITEMS:
out.notes.append(f"{key}: {len(items) - MAX_ITEMS} more items not collected")
return out
def _item(key: str, client: Client, token: str, item: Any, out: Collected, strict: bool,
local: Local | None = None) -> None:
if not isinstance(item, dict):
_fail(strict, out, f"{key}: malformed item")
return
name = str(item.get("name") or item.get("kind") or "plik")[:200]
path = rules.safe_download(item.get("download"))
expected = item.get("sha256")
if path is None or not rules.is_sha256(expected):
_fail(strict, out, f"{key}: item {name!r} has no usable download or sha256")
return
commit = item.get("commit_sha")
data = local(str(commit), expected) if (local is not None and commit) else None
if data is None:
try:
got = client.request("GET", path, token=token, accept="*/*")
except ModuleCallError:
_fail(strict, out, f"{key}: {name!r} unreachable")
return
if not got.ok:
_fail(strict, out, f"{key}: {name!r} answered {got.status}")
return
data = got.body
else:
out.notes.append(f"{key}: {name!r} read from Galena's own copy at {str(commit)[:12]}")
actual = rules.sha256(data)
if actual != expected:
if str(item.get("kind")) in LENIENT_KINDS:
out.notes.append(f"{key}: {name!r} sha256 differs from the item's (a fingerprint of "
"the unmasked card) - kept as received")
else:
_fail(strict, out, f"{key}: {name!r} does not match its sha256 - not kept")
return
out.files.append({"name": name, "kind": str(item.get("kind") or "")[:100], "sha256": actual,
"data": data,
"source": {"module": key, "id": str(item.get("source_id") or "")[:200] or None,
"commit": str(commit)[:64] if commit else None}})
def seal(manifest: bytes, *, client: Client | None = None) -> tuple[bytes | None, str | None]:
"""Parafa's detached CMS over the manifest, with ARCHIVE_READER_TOKEN: `(p7s, None)`, or
`(None, why)` - an export without the seal says so rather than failing."""
settings = get_settings()
if client is None:
url = (settings.parafa_base_url or "").strip()
client = ModuleClient(url, service="Parafa", max_body=SEAL_MAX) if url else None
if client is None:
return None, "Parafa is not configured: manifest.json is not sealed"
token = settings.archive_reader_token
if not token:
return None, "ARCHIVE_READER_TOKEN is not set: manifest.json is not sealed"
if len(manifest) > SEAL_MAX:
return None, "manifest.json is over 1 MB: not sealed"
try:
got = client.request("POST", "/seal", token=token, body=manifest,
content_type="application/octet-stream",
accept="application/pkcs7-signature")
except ModuleCallError:
return None, "Parafa is unreachable: manifest.json is not sealed"
if not got.ok or not got.body:
return None, f"Parafa answered {got.status}: manifest.json is not sealed"
return got.body, None
+157
View File
@@ -0,0 +1,157 @@
"""The contract archive's pure rules (spec 2026-11-25 part B, Atrium#53 step 6) - no database, no
network, so every one of them is tested DB-free (`tests/test_archive_unit.py`).
* **Manifest + fingerprint.** The manifest is canonical JSON (sorted keys, no spaces, UTF-8); the
package's fingerprint is the sha256 of exactly those bytes, which are also what the export ships
as `manifest.json` and what Parafa seals - so `sha256sum manifest.json` IS the fingerprint.
* **Retention** from the LIVE card: end date + limitation period + retention period (years), both
set per contract type by a moderator. No end date, no type, or no setting for the type: no due
date, and nothing is ever overdue on a guess.
* **Disposal** needs two different moderators, nothing held and the due date passed. The refusal
order is fixed: 404 (no package) -> 409 (state: disposed, held, not overdue, request missing or
already open) -> 403 (the same person approving their own request) -> 422 (no basis).
"""
from __future__ import annotations
import datetime as dt
import hashlib
import json
import re
from dataclasses import dataclass
from typing import Any
from ..errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
MANIFEST_FORMAT = "galena-archive/1"
#: Where a package's files sit inside the export ZIP; the manifest names each by this path.
FILES_DIR = "pliki"
MAX_YEARS = 100
MAX_REASON = 2000
_SHA256 = re.compile(r"[0-9a-f]{64}")
_SAFE = re.compile(r"[^A-Za-z0-9._-]+")
def canonical(obj: Any) -> bytes:
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
default=str).encode("utf-8")
def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def is_sha256(value: Any) -> bool:
return isinstance(value, str) and bool(_SHA256.fullmatch(value))
def safe_name(name: Any, index: int) -> str:
"""`<NN>-<name>`: a ZIP member name that cannot climb out of `pliki/` nor collide."""
base = _SAFE.sub("_", str(name or "plik").replace("\\", "/").rsplit("/", 1)[-1]).strip("._")
return f"{index:02d}-{(base or 'plik')[:120]}"
def safe_download(path: Any) -> str | None:
"""The contract's `download`, relative to the module's /api/v1/, as a client path; None when it
is not a plain relative path (absolute, a scheme, `..`, a backslash) - never followed."""
if not isinstance(path, str) or not path or len(path) > 1000:
return None
if path.startswith("/") or "://" in path or "\\" in path or "//" in path:
return None
if any(part in ("", ".", "..") for part in path.split("?", 1)[0].split("/")):
return None
if any(ord(c) < 33 for c in path):
return None
return "/" + path
def build_manifest(*, document_id: str, card_id: str, card_number: str, version: int,
created_at: str, created_by: str | None, trigger: str,
files: list[dict], notes: list[str]) -> dict:
"""`files`: `{path, name, kind, sha256, size, source: {module, id, commit}}` each."""
return {"format": MANIFEST_FORMAT, "document_id": document_id, "card_id": card_id,
"card_number": card_number, "version": version, "created_at": created_at,
"created_by": created_by, "trigger": trigger,
"files": sorted(files, key=lambda f: f["path"]), "notes": list(notes)}
def fingerprint(manifest: dict) -> tuple[bytes, str]:
data = canonical(manifest)
return data, sha256(data)
# ── retention ─────────────────────────────────────────────────────────────────
def add_years(day: dt.date, years: int) -> dt.date:
try:
return day.replace(year=day.year + years)
except ValueError: # 29 February into a common year
return day.replace(year=day.year + years, day=28)
def check_years(value: Any, field: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= MAX_YEARS:
raise ValidationError(f"{field} must be a whole number of years, 0-{MAX_YEARS}.",
{"code": "retention_invalid", "field": field})
return value
def due_date(ends_on: dt.date | None, rule: tuple[int, int] | None) -> dt.date | None:
"""`rule` = (limitation_years, retention_years) of the card's contract type, or None."""
if ends_on is None or rule is None:
return None
return add_years(ends_on, rule[0] + rule[1])
def is_overdue(due: dt.date | None, today: dt.date) -> bool:
return due is not None and due < today
# ── disposal ──────────────────────────────────────────────────────────────────
@dataclass(frozen=True)
class DisposalState:
has_package: bool
disposed: bool
held: bool
overdue: bool
open_request_by: str | None # who asked, while a request waits; None = none waits
def _reason(text: Any) -> str:
if not isinstance(text, str) or not text.strip():
raise ValidationError("Give the basis.", {"code": "reason_required"})
if len(text) > MAX_REASON:
raise ValidationError("The basis is too long.", {"code": "reason_too_long"})
return text.strip()
def _common(state: DisposalState) -> None:
if not state.has_package:
raise NotFoundError("Not found.")
if state.disposed:
raise ConflictError("This package has been disposed of.", {"code": "already_disposed"})
if state.held:
raise ConflictError("A legal hold blocks disposal.", {"code": "legal_hold"})
if not state.overdue:
raise ConflictError("The retention period has not passed.", {"code": "not_overdue"})
def check_request(state: DisposalState, basis: Any) -> str:
_common(state)
if state.open_request_by is not None:
raise ConflictError("A disposal request is already waiting.", {"code": "request_open"})
return _reason(basis)
def check_approve(state: DisposalState, actor_id: str, note: Any = None) -> str | None:
_common(state)
if state.open_request_by is None:
raise ConflictError("No disposal request waits.", {"code": "no_request"})
if state.open_request_by == actor_id:
raise AuthorizationError("A second moderator must approve the disposal.",
{"code": "same_person"})
if note is None or note == "":
return None
return _reason(note)
def check_hold_reason(reason: Any) -> str:
return _reason(reason)
+20 -2
View File
@@ -31,7 +31,7 @@ from dredd_core import events as core_events
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from . import cards
from . import archive, cards
log = logging.getLogger("galena.events")
@@ -101,13 +101,24 @@ def _on_card_event(db: DbSession, event: core_events.Event) -> str:
return cards.apply_event(db, node_id=document_id, event=event)
def _on_signed(db: DbSession, event: core_events.Event) -> str:
"""`document.signed` / `workflow.signed_on_paper`: the card moves forward as before, and a
signed card goes on the archive's work list - its package is made by `archive.process_pending`
with the technical account, outside this transaction's event (spec 2026-11-25 part B)."""
result = _on_card_event(db, event)
document_id = _galena_document(event)
if document_id is not None:
archive.enqueue(db, node_id=document_id, reason=event.kind, event_id=str(event.id))
return result
def receive(db: DbSession, *, limit: int = 200) -> core_events.ReceiveResult:
"""One pass over the log after this module's cursor. No commit."""
settings = get_settings()
return core_events.receive(
db, consumer=settings.module_slug,
handlers={WORKFLOW_APPROVED: _on_workflow_approved,
SIGNED_ON_PAPER: _on_card_event, DOCUMENT_SIGNED: _on_card_event,
SIGNED_ON_PAPER: _on_signed, DOCUMENT_SIGNED: _on_signed,
ROUND_RECEIVED: _on_card_event, ANALYSIS_ACCEPTED: _on_analysis_accepted},
sources={WORKFLOW_APPROVED: [*settings.workflow_event_roles_list, settings.db_app_role],
SIGNED_ON_PAPER: settings.workflow_event_roles_list,
@@ -123,6 +134,13 @@ def _pass() -> int:
with SessionLocal() as db:
result = receive(db)
db.commit()
try:
with SessionLocal() as db:
if archive.process_pending(db):
log.info("archive: signed contracts archived")
db.commit()
except Exception: # noqa: BLE001 - the archive's work list is retried by a moderator
log.exception("archive: automatic archiving failed")
if result.applied or result.refused:
log.info("events: %d read, %d applied, %d ignored, %d refused", result.read, result.applied,
result.ignored, result.refused)
+2
View File
@@ -196,6 +196,8 @@ def convert_to_project(db: DbSession, node: Node) -> Node:
def delete(db: DbSession, node: Node) -> None:
from . import archive
archive.assert_deletable(db, node) # 409 archived_contract: evidence outlives the drive
if node.kind == NodeKind.project:
from . import git_facade
git_facade.remove_project(node.id)
+260
View File
@@ -0,0 +1,260 @@
"""The contract archive's pure rules and its collector, DB-free (spec 2026-11-25 part B)."""
from __future__ import annotations
import datetime as dt
import hashlib
import json
import pytest
from dredd_core.module_client import ModuleCallError, ModuleResponse
from app.errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
from app.services import archive_collect as collector
from app.services import archive_rules as rules
DOC = "11111111-1111-1111-1111-111111111111"
# ── manifest + fingerprint ────────────────────────────────────────────────────
def _manifest(**over):
kw = dict(document_id=DOC, card_id="c", card_number="UM-2026-0001", version=1,
created_at="2026-11-27T10:00:00+00:00", created_by=None, trigger="auto",
files=[{"path": "pliki/02-b", "sha256": "b" * 64},
{"path": "pliki/01-a", "sha256": "a" * 64}],
notes=["agora: nothing on this document"])
kw.update(over)
return rules.build_manifest(**kw)
def test_fingerprint_is_the_sha256_of_the_exact_manifest_bytes():
data, fp = rules.fingerprint(_manifest())
assert fp == hashlib.sha256(data).hexdigest()
assert json.loads(data)["files"][0]["path"] == "pliki/01-a" # sorted, stable
assert b" " not in data.replace(b"agora: nothing on this document", b"")
assert rules.fingerprint(_manifest())[1] == fp # deterministic
def test_any_change_moves_the_fingerprint():
fp = rules.fingerprint(_manifest())[1]
assert rules.fingerprint(_manifest(version=2))[1] != fp
assert rules.fingerprint(_manifest(notes=[]))[1] != fp
def test_safe_names_and_downloads():
assert rules.safe_name("../../etc/passwd", 3) == "03-passwd"
assert rules.safe_name("Umowa podpisana.pdf", 1) == "01-Umowa_podpisana.pdf"
assert rules.safe_name("", 2) == "02-plik"
assert rules.safe_download("signing/x/file") == "/signing/x/file"
for bad in ("/abs", "http://evil/x", "a/../b", "a//b", "a\\b", "", None, "a b"):
assert rules.safe_download(bad) is None
# ── retention ─────────────────────────────────────────────────────────────────
def test_due_date_is_end_plus_limitation_plus_retention():
assert rules.due_date(dt.date(2020, 3, 31), (6, 4)) == dt.date(2030, 3, 31)
assert rules.due_date(dt.date(2024, 2, 29), (1, 0)) == dt.date(2025, 2, 28)
def test_no_end_date_or_no_rule_means_never_overdue():
assert rules.due_date(None, (6, 4)) is None
assert rules.due_date(dt.date(2000, 1, 1), None) is None
assert not rules.is_overdue(None, dt.date(2100, 1, 1))
due = dt.date(2030, 1, 1)
assert not rules.is_overdue(due, due)
assert rules.is_overdue(due, due + dt.timedelta(days=1))
@pytest.mark.parametrize("bad", [-1, 101, 1.5, "3", True, None])
def test_years_are_bounded_whole_numbers(bad):
with pytest.raises(ValidationError):
rules.check_years(bad, "retention_years")
# ── two-person disposal, holds, refusal order ────────────────────────────────
def _state(**over):
kw = dict(has_package=True, disposed=False, held=False, overdue=True, open_request_by=None)
kw.update(over)
return rules.DisposalState(**kw)
def test_request_then_a_different_moderator_approves():
assert rules.check_request(_state(), " basis ") == "basis"
assert rules.check_approve(_state(open_request_by="alice"), "bob") is None
assert rules.check_approve(_state(open_request_by="alice"), "bob", "ok") == "ok"
def test_the_same_person_cannot_approve_their_own_request():
with pytest.raises(AuthorizationError):
rules.check_approve(_state(open_request_by="alice"), "alice")
def test_a_hold_blocks_request_and_approval():
with pytest.raises(ConflictError) as e:
rules.check_request(_state(held=True), "x")
assert e.value.extra["code"] == "legal_hold"
with pytest.raises(ConflictError):
rules.check_approve(_state(held=True, open_request_by="alice"), "bob")
def test_not_overdue_disposed_and_open_request_are_409():
for state, code in ((_state(overdue=False), "not_overdue"),
(_state(disposed=True), "already_disposed"),
(_state(open_request_by="a"), "request_open")):
with pytest.raises(ConflictError) as e:
rules.check_request(state, "x")
assert e.value.extra["code"] == code
with pytest.raises(ConflictError) as e:
rules.check_approve(_state(), "bob")
assert e.value.extra["code"] == "no_request"
def test_refusal_order_404_409_403_422():
with pytest.raises(NotFoundError): # 404 beats everything
rules.check_approve(_state(has_package=False, held=True, open_request_by="a"), "a", "")
with pytest.raises(ConflictError): # 409 before 403
rules.check_approve(_state(held=True, open_request_by="a"), "a")
with pytest.raises(AuthorizationError): # 403 before 422
rules.check_approve(_state(open_request_by="a"), "a", "x" * 5000)
with pytest.raises(ValidationError): # 422 last
rules.check_request(_state(), " ")
with pytest.raises(ValidationError):
rules.check_hold_reason("")
# ── the collector, against fake modules ──────────────────────────────────────
PDF = b"%PDF-1.7 signed"
def _resp(status, body=b"", *, json_body=None):
if json_body is not None:
body = json.dumps(json_body).encode()
return ModuleResponse(status, {}, body)
class Fake:
def __init__(self, index=None, files=None, *, status=200, down=False):
self.index, self.files, self.status, self.down = index, files or {}, status, down
self.calls = []
def request(self, method, path, *, token, params=None, **kw):
self.calls.append((method, path, token, params))
if self.down:
raise ModuleCallError("down", {"code": "unreachable"})
if path == "/evidence":
if self.status != 200:
return _resp(self.status)
return _resp(200, json_body=self.index)
if path in self.files:
return _resp(200, self.files[path])
return _resp(404)
def _parafa(sha=None):
return Fake({"module": "parafa", "document_id": DOC, "note": None, "items": [
{"kind": "signed_pdf", "name": "umowa.pdf", "sha256": sha or hashlib.sha256(PDF).hexdigest(),
"source_id": "req-1", "commit_sha": "abc1234", "download": "signing/req-1/file"}]},
{"/signing/req-1/file": PDF})
def _modules(**over):
mods = {"parafa": _parafa(), "workflow": Fake(status=404), "agora": None,
"arbiter": Fake({"module": "arbiter", "items": [], "note": "no accepted analysis"})}
mods.update(over)
return mods
def test_collects_and_verifies_with_notes_for_what_is_missing():
got = collector.collect(DOC, token="t", modules=_modules(), strict=True)
assert [f["name"] for f in got.files] == ["umowa.pdf"]
f = got.files[0]
assert f["data"] == PDF and f["source"] == {"module": "parafa", "id": "req-1", "commit": "abc1234"}
assert "workflow: nothing on this document" in got.notes
assert "agora: not configured - nothing collected" in got.notes
assert "arbiter: no accepted analysis" in got.notes
parafa = _modules()["parafa"]
collector.collect(DOC, token="t", modules={"parafa": parafa}, strict=False)
assert parafa.calls[0] == ("GET", "/evidence", "t", {"document_id": DOC})
def test_a_hash_mismatch_is_never_kept():
mods = _modules(parafa=_parafa(sha="0" * 64))
got = collector.collect(DOC, token="t", modules=mods, strict=False)
assert got.files == [] and any("does not match" in n for n in got.notes)
with pytest.raises(collector.CollectFailed):
collector.collect(DOC, token="t", modules=_modules(parafa=_parafa(sha="0" * 64)), strict=True)
def test_unreachable_is_a_note_by_hand_and_a_retry_automatically():
got = collector.collect(DOC, token="t", modules=_modules(workflow=Fake(down=True)), strict=False)
assert "workflow: unreachable" in got.notes and len(got.files) == 1
with pytest.raises(collector.CollectFailed):
collector.collect(DOC, token="t", modules=_modules(workflow=Fake(down=True)), strict=True)
def test_401_is_a_note_by_hand_and_a_retry_automatically():
got = collector.collect(DOC, token="t", modules=_modules(workflow=Fake(status=401)), strict=False)
assert "workflow: answered 401" in got.notes
with pytest.raises(collector.CollectFailed):
collector.collect(DOC, token="t", modules=_modules(workflow=Fake(status=401)), strict=True)
def test_a_download_outside_the_api_is_refused():
bad = Fake({"items": [{"kind": "x", "name": "x", "sha256": "a" * 64, "source_id": "1",
"commit_sha": None, "download": "../../admin"}]})
got = collector.collect(DOC, token="t", modules={"parafa": bad}, strict=False)
assert got.files == [] and bad.calls == [("GET", "/evidence", "t", {"document_id": DOC})]
def test_no_token_automatically_is_a_retry():
with pytest.raises(collector.CollectFailed):
collector.collect(DOC, token=None, modules=_modules(), strict=True)
class _Sealer:
def __init__(self, status=200, down=False):
self.status, self.down, self.sent = status, down, None
def request(self, method, path, *, token, body=None, **kw):
if self.down:
raise ModuleCallError("down", {"code": "unreachable"})
self.sent = (method, path, token, body)
return _resp(self.status, b"CMS" if self.status == 200 else b"")
def test_seal_through_parafa_or_say_why_not(monkeypatch):
from app.config import get_settings
monkeypatch.setattr(get_settings(), "archive_reader_token", "reader")
s = _Sealer()
assert collector.seal(b"{}", client=s) == (b"CMS", None)
assert s.sent == ("POST", "/seal", "reader", b"{}")
p7s, why = collector.seal(b"{}", client=_Sealer(down=True))
assert p7s is None and "unreachable" in why
monkeypatch.setattr(get_settings(), "parafa_base_url", "")
p7s, why = collector.seal(b"{}")
assert p7s is None and "not configured" in why
monkeypatch.setattr(get_settings(), "archive_reader_token", "")
assert collector.seal(b"{}", client=_Sealer())[0] is None
def test_an_item_stored_in_galena_is_read_locally_never_fetched():
scan = b"scan bytes"
wf = Fake({"items": [{"kind": "paper_scan", "name": "skan.pdf",
"sha256": hashlib.sha256(scan).hexdigest(), "source_id": "run-1",
"commit_sha": "abc1234", "download": "galena/callback"}]})
seen = []
def local(commit, sha):
seen.append((commit, sha))
return scan if commit == "abc1234" else None
got = collector.collect(DOC, token="t", modules={"workflow": wf}, strict=True, local=local)
assert got.files[0]["data"] == scan and seen
assert [c[1] for c in wf.calls] == ["/evidence"] # no call back into Galena
def test_arbiters_accepted_card_is_kept_with_a_note_when_its_hash_differs():
card = b'{"masked": true}'
arb = Fake({"items": [{"kind": "accepted_card", "name": "karta.json", "sha256": "f" * 64,
"source_id": "acc-1", "commit_sha": None, "download": "cards/acc-1"}]},
{"/cards/acc-1": card})
got = collector.collect(DOC, token="t", modules={"arbiter": arb}, strict=True)
assert got.files[0]["data"] == card and any("kept as received" in n for n in got.notes)
+5 -2
View File
@@ -186,10 +186,13 @@ def test_0010_is_guarded_and_carries_no_bind_parameter_lookalikes():
def test_0007_guards_the_tables_0010_creates():
r7 = _revision("0007_shared_identity.py")
# `0010`'s two, `0012`'s three (approval workflows) and `0014`'s register copies.
# `0010`'s two, `0012`'s three (approval workflows), `0014`'s register copies and `0015`'s
# archive tables that name a person.
assert r7._LATER_TABLES == {"document_meta", "table_view", "workflow_template",
"document_workflow", "workflow_event", "counterparty",
"counterparty_contact"}
"counterparty_contact", "archive_package",
"archive_disposal_request", "archive_disposal", "archive_hold",
"archive_retention"}
plain = 'ALTER TABLE "node" DROP CONSTRAINT IF EXISTS "x"'
assert r7._if_table(r7._statement_table(plain), plain) == plain
later = 'ALTER TABLE "table_view" DROP CONSTRAINT IF EXISTS "x"'
+1 -1
View File
@@ -709,7 +709,7 @@ def test_the_constraints_are_dropped_before_the_rows_move_and_added_after():
rev = _revision()
statements = repoint_identity_fks_sql("dredd", Base.metadata)
drops, adds = rev._constraint_phases(statements)
assert len(drops) == len(adds) == 17
assert len(drops) == len(adds) == 24 # 17 + the archive's seven person columns (0015)
assert all(" DROP CONSTRAINT " in s for s in drops)
assert all(" ADD CONSTRAINT " in s for s in adds)
# Every drop precedes every add, which is the whole property.
+117
View File
@@ -0,0 +1,117 @@
"""The contract archive end to end (spec 2026-11-25 part B), against a real Postgres: a package by
hand, its versions, read access, export, retention, holds, two-person disposal and the refusal to
delete. The other modules are not configured, so their absence is in the manifest's notes.
Auto-skips unless GALENA_RUN_INTEGRATION=1 with a migrated + seeded database."""
from __future__ import annotations
import io
import json
import os
import uuid
import zipfile
import pytest
RUN = os.environ.get("GALENA_RUN_INTEGRATION") == "1"
pytestmark = pytest.mark.skipif(
not RUN, reason="set GALENA_RUN_INTEGRATION=1 with a migrated + seeded Postgres")
if RUN:
from fastapi.testclient import TestClient
from app.config import get_settings
from app.main import app
settings = get_settings()
API = "/api/v1"
def _client(email=None, password=None):
c = TestClient(app)
r = c.post(f"{API}/auth/login", json={"email": email or settings.bootstrap_admin_email,
"password": password or settings.bootstrap_admin_password})
assert r.status_code == 200, r.text
return c
def _person(admin, *, is_admin=False):
email = f"a-{uuid.uuid4().hex[:8]}@example.com"
assert admin.post(f"{API}/users", json={"email": email, "full_name": "A", "password": "userpass12",
"is_admin": is_admin}).status_code in (200, 201)
return _client(email, "userpass12")
def test_archive_lifecycle(monkeypatch):
admin = _client()
second = _person(admin, is_admin=True) # standalone: an administrator moderates
outsider = _person(admin)
tag = uuid.uuid4().hex[:6]
ws = admin.post(f"{API}/nodes", json={"parent_id": None, "kind": "workspace",
"name": f"WS {tag}"}).json()
proj = admin.post(f"{API}/nodes", json={"parent_id": ws["id"], "kind": "project",
"name": "Umowa"}).json()
assert admin.put(f"{API}/projects/{proj['id']}/document",
json={"doc_type": "umowa"}).status_code == 200
field = admin.post(f"{API}/admin/register-fields",
json={"label": f"Typ {tag}", "kind": "text"}).json()
monkeypatch.setattr(settings, "archive_type_field", field["key"])
assert admin.patch(f"{API}/projects/{proj['id']}/card", json={
"ends_on": "2000-01-31", "custom_fields": {field["key"]: f"najem-{tag}"}}).status_code == 200
pid = proj["id"]
r = admin.post(f"{API}/projects/{pid}/archive", data={"note": "papierowa"},
files={"file": ("skan.pdf", b"%PDF scan", "application/pdf")})
assert r.status_code == 200, r.text
assert r.json()["version"] == 1
assert admin.post(f"{API}/projects/{pid}/archive", data={"note": "aneks"}).json()["version"] == 2
view = admin.get(f"{API}/projects/{pid}/archive").json()
assert [p["version"] for p in view["packages"]] == [1, 2]
v1 = view["packages"][0]
assert {f["kind"] for f in v1["files"]} == {"card_snapshot", "upload"}
assert any("parafa: not configured" in n for n in v1["notes"])
assert view["due_on"] is None and view["overdue"] is False # no retention set yet
assert outsider.get(f"{API}/projects/{pid}/archive").status_code == 404
assert outsider.get(f"{API}/projects/{pid}/archive/export").status_code == 404
assert outsider.post(f"{API}/archive/holds", json={
"target_type": "card", "target_id": pid, "reason": "x"}).status_code == 403
z = admin.get(f"{API}/projects/{pid}/archive/export?version=1")
assert z.status_code == 200 and z.headers["x-archive-sealed"] == "false"
with zipfile.ZipFile(io.BytesIO(z.content)) as zf:
manifest = zf.read("manifest.json")
assert "NIEPODPISANY.txt" in zf.namelist()
import hashlib
assert hashlib.sha256(manifest).hexdigest() == v1["fingerprint"]
for f in json.loads(manifest)["files"]:
assert hashlib.sha256(zf.read(f["path"])).hexdigest() == f["sha256"]
assert admin.delete(f"{API}/nodes/{pid}").json()["code"] == "archived_contract"
assert admin.delete(f"{API}/nodes/{ws['id']}").status_code == 409
# Retention: not overdue -> 409; set it and the card is overdue.
assert admin.post(f"{API}/projects/{pid}/archive/disposal",
json={"reason": "x"}).json()["code"] == "not_overdue"
assert admin.put(f"{API}/archive/retention/najem-{tag}",
json={"limitation_years": 3, "retention_years": 5}).status_code == 200
assert any(r["project_id"] == pid for r in admin.get(f"{API}/archive/overdue").json())
hold = admin.post(f"{API}/archive/holds", json={"target_type": "card", "target_id": pid,
"reason": "spór"}).json()
assert admin.post(f"{API}/projects/{pid}/archive/disposal",
json={"reason": "termin"}).json()["code"] == "legal_hold"
assert admin.post(f"{API}/archive/holds/{hold['id']}/lift",
json={"reason": "ugoda"}).status_code == 200
assert admin.post(f"{API}/projects/{pid}/archive/disposal",
json={"reason": "termin minął"}).status_code == 200
assert admin.post(f"{API}/projects/{pid}/archive/disposal/approve",
json={}).json()["code"] == "same_person"
done = second.post(f"{API}/projects/{pid}/archive/disposal/approve", json={})
assert done.status_code == 200, done.text
assert [p["version"] for p in done.json()["protocol"]["packages"]] == [1, 2]
assert admin.get(f"{API}/projects/{pid}/archive/export").json()["code"] == "already_disposed"
disposals = admin.get(f"{API}/archive/disposals").json()
assert any(p["project_id"] == pid for p in disposals["protocols"])
assert len(admin.get(f"{API}/projects/{pid}/archive").json()["packages"]) == 2 # rows stay
+156 -2
View File
@@ -213,7 +213,7 @@ function isModerator() { return !!(state.user && state.user.is_moderator); }
function renderTopActions() {
$('navToggle').innerHTML = svg(ICN.sidebar); $('aSearch').innerHTML = svg(ICN.search);
$('aBell').innerHTML = svg(ICN.bell); $('aDashboard').innerHTML = svg(ICN.dashboard);
$('aDrafts').innerHTML = svg(ICN.pr); $('aRegister').innerHTML = svg(ICN.list); $('aWorkflows').innerHTML = svg(ICN.checklist); $('aAdmin').innerHTML = svg(ICN.adjustments);
$('aDrafts').innerHTML = svg(ICN.pr); $('aRegister').innerHTML = svg(ICN.list); $('aArchive').innerHTML = svg(ICN.lock); $('aWorkflows').innerHTML = svg(ICN.checklist); $('aAdmin').innerHTML = svg(ICN.adjustments);
$('aPwgen').innerHTML = svg(ICN.key);
$('aOcr').innerHTML = svg(ICN.scaneye);
$('aTheme').innerHTML = svg(TH[themeMode()]); $('aUser').textContent = initials(state.user && state.user.email);
@@ -325,6 +325,7 @@ async function router() {
if (v === 'cards') return viewCards(C);
if (v === 'card' && seg[1]) return viewCard(seg[1], C);
if (v === 'fields') return viewRegisterFields(C);
if (v === 'archive') return viewArchive(C, q.view || 'list', q);
if (v === 'password') return viewPasswordGen(C);
if (v === 'ocr') return viewOcr(C);
if (v === 'settings') return viewSettings(C);
@@ -2265,7 +2266,8 @@ async function viewCard(projectId, C) {
h += cardAnalysisRow(card.accepted_analysis);
C.innerHTML = `<div class="page"><div class="page-head"><div><h1>${esc(card.name)}</h1><div class="sub"><span>Contract card</span> · <span class="mono">${esc(card.path)}</span></div></div>
<div class="page-actions">${btn('Open document', { icon: ICN.project, attrs: `data-id="${esc(card.project_id)}" onclick="go('n/'+this.dataset.id)"` })}${card.can_edit ? btn('Counterparties', { icon: ICN.list, onclick: 'cardPartiesDialog()' }) + btn('Edit', { cls: 'primary', icon: ICN.edit, onclick: 'cardEditDialog()' }) : ''}</div></div>
<div class="card"><div class="card-body"><div class="detail-rows">${h}</div></div></div></div>`;
<div class="card"><div class="card-body"><div class="detail-rows">${h}</div></div></div><div id="cardArchive"></div></div>`;
cardArchiveSection(card.project_id);
}
// The card's counterparties from the platform's register (spec 2026-11-25 part A): a search by name,
// NIP or KRS, and, when nothing fits, a new organisation (a person stays the card's text).
@@ -2566,7 +2568,158 @@ window.wfTemplateDialog = async (idx) => {
_wftRender();
};
/* ── the contract archive („Archiwum”, spec 2026-11-25 part B) ──
Lists: Archive (everyone, what they may read), and for moderators To archive, Past retention,
Legal holds, Disposals, Retention periods. The card shows its package versions. Every value esc()'d. */
const ARCH_TABS = [['list', 'Contract archive'], ['pending', 'To archive'], ['overdue', 'Past retention'], ['holds', 'Legal holds'], ['disposals', 'Disposals'], ['retention', 'Retention periods']];
function archTabs(view) {
return ARCH_TABS.filter(([v]) => v === 'list' || isModerator()).map(([v, label]) => btn(label, { cls: v === view ? 'primary' : 'ghost', attrs: `data-v="${esc(v)}" onclick="go('archive?view='+this.dataset.v)"` })).join('');
}
function archLink(pid, label) { return `<a data-id="${esc(pid)}" onclick="go('card/'+this.dataset.id)">${esc(label || '—')}</a>`; }
function archTable(head, rows, empty) {
return rows.length ? `<table class="dt"><thead><tr>${head.map(h => `<th>${_card(h)}</th>`).join('')}</tr></thead><tbody>${rows.join('')}</tbody></table>` : `<div class="empty">${_card(empty)}</div>`;
}
const ARCH_FILTERS = ['counterparty', 'date_from', 'date_to', 'contract_type', 'value_min', 'value_max'];
async function viewArchive(C, view, q) {
view = ARCH_TABS.some(([v]) => v === view) && (view === 'list' || isModerator()) ? view : 'list';
setCrumb([{ label: 'Contract archive' }]);
let body = '', tools = '';
if (view === 'list') {
const p = new URLSearchParams();
for (const k of ARCH_FILTERS) if (q[k]) p.set(k, q[k]);
const rows = await api('GET', '/archive' + (p.toString() ? '?' + p : ''));
tools = `<div class="form-grid" style="margin-bottom:12px">
<label class="field"><span>Counterparty</span><input id="arQ_counterparty" value="${esc(q.counterparty || '')}"></label>
<label class="field"><span>Archived from</span><input type="date" id="arQ_date_from" value="${esc(q.date_from || '')}"></label>
<label class="field"><span>Archived to</span><input type="date" id="arQ_date_to" value="${esc(q.date_to || '')}"></label>
<label class="field"><span>Contract type</span><input id="arQ_contract_type" value="${esc(q.contract_type || '')}"></label>
<label class="field"><span>Value from</span><input type="number" id="arQ_value_min" value="${esc(q.value_min || '')}"></label>
<label class="field"><span>Value to</span><input type="number" id="arQ_value_max" value="${esc(q.value_max || '')}"></label>
</div>${btn('Search', { cls: 'primary', icon: ICN.search, onclick: 'archSearch()' })}`;
body = archTable(['Number', 'Name', 'Counterparty', 'Contract type', 'Value', 'Version', 'Archived', 'Retention until'], rows.map(r => `<tr>
<td class="mono">${archLink(r.project_id, r.card_number)}</td><td>${esc(r.name)}</td><td>${esc(r.counterparty || '')}</td><td>${esc(r.contract_type || '')}</td>
<td>${esc(r.value_amount ? r.value_amount + ' ' + (r.value_currency || '') : '')}</td><td>${esc(r.version)}</td><td>${esc((r.archived_at || '').slice(0, 10))}</td>
<td>${r.disposed ? _card('Disposed') : esc(r.due_on || '—')}${r.overdue ? ' <span class="chip">' + _card('Past retention') + '</span>' : ''}</td></tr>`), 'Nothing archived.');
} else if (view === 'pending') {
const rows = await api('GET', '/archive/pending');
body = archTable(['Number', 'Name', 'Event', 'Attempts', 'Last error', ''], rows.map(r => `<tr>
<td class="mono">${archLink(r.project_id, r.card_number)}</td><td>${esc(r.name || '')}</td><td class="mono">${esc(r.reason)}</td><td>${esc(r.attempts)}</td><td>${esc(r.last_error || '')}</td>
<td style="white-space:nowrap">${btn('Retry', { icon: ICN.refresh, attrs: `data-id="${esc(r.project_id)}" onclick="archRetry(this.dataset.id)"` })}${btn('Archive by hand', { attrs: `data-id="${esc(r.project_id)}" onclick="archManualDialog(this.dataset.id)"` })}</td></tr>`), 'Nothing waits to be archived.');
} else if (view === 'overdue') {
const rows = await api('GET', '/archive/overdue');
body = archTable(['Number', 'Name', 'Contract type', 'Retention until', 'State'], rows.map(r => `<tr>
<td class="mono">${archLink(r.project_id, r.card_number)}</td><td>${esc(r.name)}</td><td>${esc(r.contract_type || '')}</td><td>${esc(r.due_on)}</td>
<td>${r.held ? _card('Legal hold') : r.disposal_requested ? _card('Disposal requested') : ''}</td></tr>`), 'Nothing is past its retention period.');
} else if (view === 'holds') {
const rows = await api('GET', '/archive/holds');
body = archTable(['On', 'Reason', 'Set', ''], rows.map(r => `<tr>
<td>${r.target_type === 'card' ? archLink(r.target_id, r.label) : esc(r.label || r.target_id)} <span class="faint">${_card(r.target_type === 'card' ? 'card' : 'counterparty')}</span></td>
<td>${esc(r.reason)}</td><td>${esc((r.set_at || '').slice(0, 10))}</td>
<td>${btn('Lift', { attrs: `data-id="${esc(r.id)}" onclick="archLiftHold(this.dataset.id)"` })}</td></tr>`), 'No legal holds.');
tools = `<p class="faint">${_card('A hold on a card is set from the card; a hold on a counterparty blocks the disposal of every contract with it.')}</p>
<div class="form-grid"><label class="field"><span>Counterparty id</span><input id="arHoldCp" placeholder="UUID"></label><label class="field"><span>Reason</span><input id="arHoldCpReason" maxlength="2000"></label></div>${btn('Hold this counterparty', { onclick: 'archHoldCounterparty()' })}`;
} else if (view === 'disposals') {
const d = await api('GET', '/archive/disposals');
const me = state.user && state.user.id;
body = `<h3 style="margin:12px">${_card('Waiting for a second moderator')}</h3>` + archTable(['Number', 'Name', 'Basis', 'Requested', ''], d.requests.map(r => `<tr>
<td class="mono">${archLink(r.project_id, r.card_number)}</td><td>${esc(r.name || '')}</td><td>${esc(r.basis)}</td><td>${esc((r.created_at || '').slice(0, 10))}</td>
<td>${r.requested_by === me ? `<span class="faint">${_card('Your request')}</span>` : btn('Approve disposal', { cls: 'primary', attrs: `data-id="${esc(r.project_id)}" onclick="archApprove(this.dataset.id)"` })}</td></tr>`), 'No disposal requests.')
+ `<h3 style="margin:12px">${_card('Disposal protocols')}</h3>` + archTable(['Number', 'Basis', 'Fingerprints', 'Disposed'], d.protocols.map(p => `<tr>
<td class="mono">${esc(p.card_number)}</td><td>${esc(p.basis)}</td><td class="mono" style="font-size:11px">${p.packages.map(x => 'v' + esc(x.version) + ' ' + esc(x.fingerprint)).join('<br>')}</td><td>${esc((p.created_at || '').slice(0, 10))}</td></tr>`), 'No disposals yet.');
} else if (view === 'retention') {
const rows = await api('GET', '/archive/retention');
body = archTable(['Contract type', 'Limitation period (years)', 'Retention period (years)'], rows.map(r => `<tr><td>${esc(r.contract_type)}</td><td>${esc(r.limitation_years)}</td><td>${esc(r.retention_years)}</td></tr>`), 'No retention periods: nothing is past retention.');
tools = `<p class="faint">${_card('Retention ends on the card’s end date plus both periods. There are no defaults.')}</p><div class="form-grid">
<label class="field"><span>Contract type</span><input id="arRtType" maxlength="200"></label>
<label class="field"><span>Limitation period (years)</span><input type="number" min="0" max="100" id="arRtLim"></label>
<label class="field"><span>Retention period (years)</span><input type="number" min="0" max="100" id="arRtRet"></label></div>${btn('Save', { cls: 'primary', onclick: 'archSaveRetention()' })}`;
}
C.innerHTML = `<div class="page"><div class="page-head"><div><h1>Contract archive</h1><div class="sub"><span>Archived contract packages: copies, fingerprints, retention</span></div></div>
<div class="page-actions">${archTabs(view)}</div></div>${tools ? `<div class="card"><div class="card-body">${tools}</div></div>` : ''}
<div class="card"><div class="card-body" style="padding:0">${body}</div></div></div>`;
}
window.archSearch = () => {
const p = [];
for (const k of ARCH_FILTERS) { const v = $('arQ_' + k).value.trim(); if (v) p.push(encodeURIComponent(k) + '=' + encodeURIComponent(v)); }
go('archive?view=list' + (p.length ? '&' + p.join('&') : ''));
};
function archErr(e) { return (e && e.message) || _tr('Something went wrong'); }
function archReasonDialog(title, intro, label, save, run) {
dialog(_tr(title), (intro ? `<p>${_card(intro)}</p>` : '') + `<label class="field"><span>${_card(label)}</span><textarea id="arReason" maxlength="2000"></textarea></label>`, async () => {
try { await run($('arReason').value); closeModal(); router(); } catch (e) { toast(archErr(e)); }
}, save);
}
window.archRetry = async (pid) => { try { const r = await api('POST', '/archive/pending/' + pid + '/retry'); toast(r.archived ? _tr('Archived') : (r.last_error || _tr('Not archived'))); router(); } catch (e) { toast(archErr(e)); } };
window.archLiftHold = (id) => archReasonDialog('Lift the legal hold', '', 'Reason (required)', 'Lift',
(reason) => api('POST', '/archive/holds/' + id + '/lift', { reason }).then(() => toast(_tr('Hold lifted'))));
window.archHoldCard = (pid) => archReasonDialog('Set a legal hold', '', 'Reason (required)', 'Set hold',
(reason) => api('POST', '/archive/holds', { target_type: 'card', target_id: pid, reason }).then(() => toast(_tr('Hold set'))));
window.archRequestDisposal = (pid) => archReasonDialog('Request disposal', 'A second moderator must approve it.', 'Basis (required)', 'Request disposal',
(reason) => api('POST', '/projects/' + pid + '/archive/disposal', { reason }).then(() => toast(_tr('Disposal requested'))));
window.archApprove = (pid) => archReasonDialog('Approve disposal', 'The package files are removed for good. The protocol stays.', 'Note (optional)', 'Approve disposal',
(reason) => api('POST', '/projects/' + pid + '/archive/disposal/approve', { reason: reason || null }).then(() => toast(_tr('Disposed'))));
window.archHoldCounterparty = async () => {
try { await api('POST', '/archive/holds', { target_type: 'counterparty', target_id: $('arHoldCp').value.trim(), reason: $('arHoldCpReason').value }); toast(_tr('Hold set')); router(); } catch (e) { toast(archErr(e)); }
};
window.archSaveRetention = async () => {
const t = $('arRtType').value.trim(); if (!t) return toast(_tr('Name the contract type.'));
try { await api('PUT', '/archive/retention/' + encodeURIComponent(t), { limitation_years: Number($('arRtLim').value), retention_years: Number($('arRtRet').value) }); toast(_tr('Saved')); router(); } catch (e) { toast(archErr(e)); }
};
window.archManualDialog = (pid) => {
dialog(_tr('Archive by hand'), `<p class="faint">${_card('Collects the evidence the other modules hold with your own access; whatever is missing is noted in the manifest. A new package is a new version; earlier ones stay.')}</p>
<label class="field"><span>Scan (optional, e.g. an old paper contract)</span><input type="file" id="arFile"></label>
<label class="field"><span>Notes</span><textarea id="arNote" maxlength="2000"></textarea></label>`, async () => {
const fd = new FormData(); fd.append('note', $('arNote').value || ''); const f = $('arFile').files[0]; if (f) fd.append('file', f, f.name);
try {
const headers = { 'Accept': 'application/json' }; if (state.token) headers['Authorization'] = 'Bearer ' + state.token;
const res = await fetch(API + '/projects/' + pid + '/archive', { method: 'POST', body: fd, credentials: 'include', headers });
const data = await res.json().catch(() => null);
if (!res.ok) throw new Error((data && (data.detail || data.title)) || res.statusText);
closeModal(); toast(_tr('Archived') + ' v' + data.version); router();
} catch (e) { toast(archErr(e)); }
}, 'Archive');
};
window.archExport = async (pid, version) => {
try {
const res = await api('GET', '/projects/' + pid + '/archive/export?version=' + encodeURIComponent(version), undefined, true);
if (!res.ok) { const d = await res.json().catch(() => null); throw new Error((d && d.detail) || res.statusText); }
if (res.headers.get('X-Archive-Sealed') !== 'true') toast(_tr('Exported without the seal: see NIEPODPISANY.txt'));
const blob = await res.blob(); const a = document.createElement('a'); a.href = URL.createObjectURL(blob);
a.download = 'archiwum-v' + version + '.zip'; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 1000);
} catch (e) { toast(archErr(e)); }
};
// The package section of the contract card (viewCard): versions, files with sha256, notes, holds, retention.
async function cardArchiveSection(pid) {
const el = $('cardArchive'); if (!el) return;
let a; try { a = await api('GET', '/projects/' + pid + '/archive'); } catch (e) { el.innerHTML = ''; return; }
const mod = a.can_moderate, disposed = !!a.disposal, me = state.user && state.user.id;
const pk = a.packages.slice().reverse().map(p => `<div style="border-top:1px solid var(--border);padding:8px 0">
<div><b>${_card('Version')} ${esc(p.version)}</b> · ${esc((p.created_at || '').slice(0, 16).replace('T', ' '))} · <span class="faint">${_card(p.trigger === 'auto' ? 'after the signature' : 'by hand')}</span>
${disposed ? '' : btn('Export ZIP', { icon: ICN.download, attrs: `data-id="${esc(pid)}" data-v="${esc(p.version)}" onclick="archExport(this.dataset.id,this.dataset.v)"` })}</div>
<div class="mono faint" style="font-size:11px">${_card('Fingerprint')} ${esc(p.fingerprint)}</div>
${p.files.map(f => `<div style="font-size:12px">${esc(f.name)} <span class="faint">(${esc(f.source_module)}${f.source_id ? ' ' + esc(f.source_id) : ''}${f.commit_sha ? ' @' + esc(f.commit_sha.slice(0, 10)) : ''}, ${esc(fmtBytes(f.size))})</span> <span class="mono faint" style="font-size:10px">${esc(f.sha256)}</span></div>`).join('')}
${p.notes.length ? `<div class="faint" style="font-size:12px">${p.notes.map(n => '· ' + esc(n)).join('<br>')}</div>` : ''}</div>`).join('');
const holds = a.holds.map(h => `<div class="banner warn">${svg(ICN.lock)}<span>${_card('Legal hold')}: ${esc(h.reason)} <span class="faint">(${_card(h.target_type === 'card' ? 'card' : 'counterparty')})</span></span>${mod ? btn('Lift', { attrs: `data-id="${esc(h.id)}" onclick="archLiftHold(this.dataset.id)"` }) : ''}</div>`).join('');
const retention = `<div class="row"><span class="k">${_card('Contract type')}</span><span>${esc(a.contract_type || '—')}</span></div>
<div class="row"><span class="k">${_card('Retention until')}</span><span>${esc(a.due_on || '—')}${a.overdue ? ' <span class="chip">' + _card('Past retention') + '</span>' : ''}</span></div>`;
const actions = mod ? (disposed ? '' : btn('Archive by hand', { icon: ICN.plus, attrs: `data-id="${esc(pid)}" onclick="archManualDialog(this.dataset.id)"` })
+ btn('Set a legal hold', { icon: ICN.lock, attrs: `data-id="${esc(pid)}" onclick="archHoldCard(this.dataset.id)"` })
+ (a.packages.length && !disposed && !a.disposal_request && a.overdue ? btn('Request disposal', { attrs: `data-id="${esc(pid)}" onclick="archRequestDisposal(this.dataset.id)"` }) : '')
+ (a.disposal_request && a.disposal_request.requested_by !== me ? btn('Approve disposal', { cls: 'primary', attrs: `data-id="${esc(pid)}" onclick="archApprove(this.dataset.id)"` }) : '')) : '';
el.innerHTML = `<div class="card"><div class="card-body"><h3>${_card('Contract archive')}</h3>
${a.pending ? `<div class="banner warn">${svg(ICN.info)}<span>${_card('Waiting to be archived')}${a.pending.last_error ? ': ' + esc(a.pending.last_error) : ''}</span></div>` : ''}
${disposed ? `<div class="banner">${svg(ICN.info)}<span>${_card('Disposed of on')} ${esc(a.disposal.created_at.slice(0, 10))}: ${esc(a.disposal.basis)}</span></div>` : ''}
${a.disposal_request ? `<div class="banner">${svg(ICN.info)}<span>${_card('Disposal requested')}: ${esc(a.disposal_request.basis)}</span></div>` : ''}
${holds}<div class="detail-rows">${retention}</div>
${pk || `<div class="faint">${_card('No package yet.')}</div>`}
<div style="margin-top:10px;display:flex;gap:8px;flex-wrap:wrap">${actions}</div></div></div>`;
if (typeof localize === 'function') localize(el);
}
const I18N = { pl: {
// The contract archive (Archiwum, spec 2026-11-25 part B).
"Contract archive": "Archiwum",
"To archive": "Do zarchiwizowania", "Past retention": "Po terminie retencji", "Legal holds": "Blokady", "Disposals": "Likwidacje", "Retention periods": "Okresy retencji", "Archived from": "Zarchiwizowano od", "Archived to": "Zarchiwizowano do", "Contract type": "Typ umowy", "Value from": "Wartość od", "Value to": "Wartość do", "Search": "Szukaj", "Retention until": "Retencja do", "Disposed": "Zlikwidowano", "Nothing archived.": "Nic nie zarchiwizowano.", "Event": "Zdarzenie", "Attempts": "Próby", "Last error": "Ostatni błąd", "Retry": "Ponów", "Archive by hand": "Archiwizuj ręcznie", "Nothing waits to be archived.": "Nic nie czeka na archiwizację.", "Legal hold": "Blokada prawna", "Disposal requested": "Wniosek o likwidację", "Nothing is past its retention period.": "Nic nie jest po terminie retencji.", "On": "Na", "Reason": "Uzasadnienie", "Set": "Założono", "Lift": "Zdejmij", "card": "karta", "counterparty": "kontrahent", "No legal holds.": "Brak blokad.", "A hold on a card is set from the card; a hold on a counterparty blocks the disposal of every contract with it.": "Blokadę karty zakłada się na karcie; blokada kontrahenta wstrzymuje likwidację każdej umowy z nim.", "Counterparty id": "Identyfikator kontrahenta", "Hold this counterparty": "Zablokuj kontrahenta", "Waiting for a second moderator": "Czeka na drugiego moderatora", "Basis": "Podstawa", "Requested": "Złożono", "Your request": "Twój wniosek", "Approve disposal": "Zatwierdź likwidację", "No disposal requests.": "Brak wniosków o likwidację.", "Disposal protocols": "Protokoły likwidacji", "Fingerprints": "Odciski", "No disposals yet.": "Brak likwidacji.", "Limitation period (years)": "Okres przedawnienia (lata)", "Retention period (years)": "Okres retencji (lata)", "No retention periods: nothing is past retention.": "Brak okresów retencji: nic nie jest po terminie.", "Retention ends on the card’s end date plus both periods. There are no defaults.": "Retencja kończy się w dniu końca umowy z karty plus oba okresy. Wartości domyślnych nie ma.", "Archived contract packages: copies, fingerprints, retention": "Paczki archiwalne umów: kopie, odciski, retencja", "Lift the legal hold": "Zdejmij blokadę prawną", "Reason (required)": "Uzasadnienie (wymagane)", "Set a legal hold": "Załóż blokadę prawną", "Set hold": "Załóż blokadę", "Request disposal": "Wnioskuj o likwidację", "A second moderator must approve it.": "Musi go zatwierdzić drugi moderator.", "Basis (required)": "Podstawa (wymagana)", "The package files are removed for good. The protocol stays.": "Pliki paczki zostaną usunięte na zawsze. Protokół zostaje.", "Collects the evidence the other modules hold with your own access; whatever is missing is noted in the manifest. A new package is a new version; earlier ones stay.": "Zbiera dowody z innych modułów Twoim dostępem; braki trafiają do manifestu. Nowa paczka to nowa wersja; wcześniejsze zostają.", "Scan (optional, e.g. an old paper contract)": "Skan (opcjonalnie, np. starej umowy papierowej)", "Notes": "Uwagi", "after the signature": "po podpisie", "by hand": "ręcznie", "Export ZIP": "Eksport ZIP", "Fingerprint": "Odcisk", "Waiting to be archived": "Czeka na archiwizację", "Disposed of on": "Zlikwidowano", "No package yet.": "Brak paczki.", "Hold lifted": "Zdjęto blokadę", "Hold set": "Założono blokadę", "Not archived": "Nie zarchiwizowano", "Name the contract type.": "Podaj typ umowy.", "Exported without the seal: see NIEPODPISANY.txt": "Wyeksportowano bez pieczęci: zob. NIEPODPISANY.txt",
'My files': 'Moje pliki', 'Favourites': 'Ulubione', 'Shared with me': 'Udostępnione mi', 'Recent': 'Ostatnie', 'Workspaces': 'Przestrzenie', 'Settings': 'Ustawienia', 'Storage': 'Pamięć',
'Dashboard': 'Pulpit', 'Drafts': 'Szkice', 'Administration': 'Administracja', 'Search workspaces, projects, folders…': 'Szukaj przestrzeni, projektów, folderów…',
'Sign in': 'Zaloguj się', 'Email': 'E-mail', 'Password': 'Hasło', 'Text versioning system': 'System wersjonowania tekstu',
@@ -2808,6 +2961,7 @@ $('loginForm').addEventListener('submit', doLogin);
$('aDashboard').onclick = () => go('dashboard');
$('aDrafts').onclick = () => go('drafts');
$('aRegister').onclick = () => go('cards');
$('aArchive').onclick = () => go('archive');
$('aWorkflows').onclick = () => go('workflows');
$('aPwgen').onclick = () => go('password');
$('aOcr').onclick = () => go('ocr');
+1
View File
@@ -123,6 +123,7 @@
<button class="iconbtn" id="aDashboard" title="Dashboard"></button>
<button class="iconbtn" id="aDrafts" title="Drafts"></button>
<button class="iconbtn" id="aRegister" title="Contract register"></button>
<button class="iconbtn" id="aArchive" title="Contract archive"></button>
<button class="iconbtn" id="aWorkflows" title="Approval workflows"></button>
<button class="iconbtn" id="aPwgen" title="Password generator"></button>
<button class="iconbtn" id="aOcr" title="Text recognition (OCR)"></button>