feat: include document artifacts in project export/import round-trip

This commit is contained in:
Арсентьев Александр
2026-09-30 12:24:49 +03:00
parent bc0e04a482
commit 8302250325
6 changed files with 1482 additions and 4 deletions
+95 -3
View File
@@ -20,6 +20,7 @@ from app.models.ks3 import KS3, KS3KS2
from app.models.payment import Payment, PaymentAllocation
from app.models.project import Project
from app.models.work_journal import WorkJournalEntry
from app.models.document_artifact import DocumentArtifact
FORMAT_NAME = "work_volume_tracker"
FORMAT_VERSION = 1
@@ -46,7 +47,7 @@ REQUIRED_FILES = (
)
# Old Task 025 archives may lack this file; import treats it as an empty journal.
OPTIONAL_FILES = ("work_journal_entries.json",)
OPTIONAL_FILES = ("work_journal_entries.json", "document_artifacts.json")
EXPORT_FILES = REQUIRED_FILES[:-1] + OPTIONAL_FILES + ("checksums.json",)
@@ -184,6 +185,19 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
.order_by(WorkJournalEntry.id)
.all()
)
# Official artifacts for issued/cancelled KS-2 and KS-3 only.
ks2_statuses = {k.id: k.status for k in ks2_docs}
ks3_statuses = {k.id: k.status for k in ks3_docs}
eligible_doc_ids = {
"KS2": {kid for kid, st in ks2_statuses.items() if st in ("issued", "cancelled")},
"KS3": {kid for kid, st in ks3_statuses.items() if st in ("issued", "cancelled")},
}
document_artifacts = (
db.query(DocumentArtifact)
.filter(DocumentArtifact.project_id == project_id)
.order_by(DocumentArtifact.id)
.all()
)
return {
"project": project,
@@ -203,6 +217,8 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
"payments": payments,
"payment_allocations": payment_allocations,
"work_journal_entries": work_journal_entries,
"document_artifacts": document_artifacts,
"eligible_doc_ids": eligible_doc_ids,
}
@@ -616,6 +632,65 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
for e in graph.get("work_journal_entries", [])
]
# Official artifacts (issued/cancelled KS-2/KS-3 only)
from app.services.document_artifact_service import compute_content_hash
from app.config import document_storage_root
eligible = graph.get("eligible_doc_ids", {})
ks2_map = keys["ks2"]
ks3_map = keys["ks3"]
document_artifacts_records = []
artifact_blobs: dict[str, bytes] = {}
storage_root = document_storage_root()
for art in graph.get("document_artifacts", []):
if art.document_type == "KS2":
eligible_ids = eligible.get("KS2", set())
doc_export_id = ks2_map.get(art.document_id)
elif art.document_type == "KS3":
eligible_ids = eligible.get("KS3", set())
doc_export_id = ks3_map.get(art.document_id)
else:
continue
# Only issued/cancelled documents
if art.document_id not in eligible_ids:
continue
if doc_export_id is None:
raise ProjectExportError(
f"Artifact {art.id} references unknown document {art.document_type}:{art.document_id}"
)
# Physical file must exist and match content_hash
from app.services.document_artifact_service import resolve_storage_path
file_path = resolve_storage_path(art.storage_key)
if not file_path.is_file():
raise ProjectExportError(
f"Artifact file not found for {art.document_type}:{art.document_id} ({art.format})"
)
file_bytes = file_path.read_bytes()
actual_hash = compute_content_hash(file_bytes)
if actual_hash != art.content_hash:
raise ProjectExportError(
f"Artifact file hash mismatch for {art.document_type}:{art.document_id}"
)
ext = "xlsx" if art.format == "xlsx" else "docx" if art.format == "docx" else art.format
archive_path = f"artifacts/{art.document_type.lower()}/{art.id}.{ext}"
artifact_blobs[archive_path] = file_bytes
document_artifacts_records.append({
"export_id": f"document_artifact:{art.id:08d}",
"source_id": art.id,
"document_type": art.document_type,
"document_export_id": doc_export_id,
"format": art.format,
"template_type": art.template_type,
"template_version": art.template_version,
"content_hash": art.content_hash,
"input_hash": art.input_hash,
"is_current": bool(art.is_current),
"generated_at": _iso(art.generated_at),
"archive_path": archive_path,
})
counts = {
"boq_documents": len(boq_documents),
"systems": len(systems),
@@ -633,6 +708,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"payments": len(payments),
"payment_allocations": len(payment_allocations),
"work_journal_entries": len(work_journal_entries),
"document_artifacts": len(document_artifacts_records),
}
manifest = {
"format": FORMAT_NAME,
@@ -643,7 +719,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"counts": counts,
}
return {
files = {
"manifest.json": manifest,
"project.json": project_record,
"boq_documents.json": boq_documents,
@@ -662,12 +738,25 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"payments.json": payments,
"payment_allocations.json": payment_allocations,
"work_journal_entries.json": work_journal_entries,
"document_artifacts.json": document_artifacts_records,
}
return {**files, "__artifact_blobs__": artifact_blobs}
def build_archive(files: dict[str, Any]) -> tuple[bytes, str]:
"""Serialize payload dict to a ZIP with checksums. Returns (zip_bytes, filename)."""
parts: dict[str, bytes] = {name: _dumps(payload) for name, payload in files.items()}
artifact_blobs = files.pop("__artifact_blobs__", {}) if "__artifact_blobs__" in files else {}
parts: dict[str, bytes] = {}
for name, payload in files.items():
if name == "__artifact_blobs__":
continue
if isinstance(payload, bytes):
parts[name] = payload
else:
parts[name] = _dumps(payload)
# Physical artifact files
for path, data in artifact_blobs.items():
parts[path] = data
checksums = {name: _sha256(data) for name, data in parts.items()}
parts["checksums.json"] = _dumps(checksums)
@@ -677,6 +766,9 @@ def build_archive(files: dict[str, Any]) -> tuple[bytes, str]:
if name not in parts:
raise ProjectExportError(f"В архиве отсутствует обязательный файл {name}")
zf.writestr(name, parts[name])
# Physical artifacts (always present if collected)
for path in sorted(artifact_blobs.keys()):
zf.writestr(path, artifact_blobs[path])
project_name = files.get("manifest.json", {}).get("project_name", "проект")
return buf.getvalue(), _safe_archive_filename(project_name)