feat: include document artifacts in project export/import round-trip
This commit is contained in:
@@ -19,6 +19,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
|
||||
from app.exporters.project_export import (
|
||||
FORMAT_NAME,
|
||||
FORMAT_VERSION,
|
||||
@@ -49,6 +50,7 @@ _LIST_FILES = (
|
||||
"payments.json",
|
||||
"payment_allocations.json",
|
||||
"work_journal_entries.json",
|
||||
"document_artifacts.json",
|
||||
)
|
||||
|
||||
_ALLOWED_AGREEMENT_STATUS = {"draft", "approved"}
|
||||
@@ -75,6 +77,7 @@ _REQUIRED_FIELDS: dict[str, tuple[str, ...]] = {
|
||||
"payments.json": ("export_id", "date", "amount", "currency", "status"),
|
||||
"payment_allocations.json": ("export_id", "payment_export_id", "ks3_export_id", "amount"),
|
||||
"work_journal_entries.json": ("export_id", "type", "text"),
|
||||
"document_artifacts.json": ("export_id", "document_type", "document_export_id", "format", "content_hash", "archive_path"),
|
||||
}
|
||||
|
||||
|
||||
@@ -140,6 +143,11 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
|
||||
wanted = [n for n in REQUIRED_FILES] + [n for n in OPTIONAL_FILES if n in names]
|
||||
raw: dict[str, bytes] = {n: zf.read(n) for n in wanted}
|
||||
# Physical artifact files (any path under artifacts/)
|
||||
artifact_files: dict[str, bytes] = {}
|
||||
for name in names:
|
||||
if name.startswith("artifacts/") and not name.endswith("/"):
|
||||
artifact_files[name] = zf.read(name)
|
||||
|
||||
try:
|
||||
checksums = json.loads(raw["checksums.json"].decode("utf-8"))
|
||||
@@ -156,6 +164,13 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
if expected != actual:
|
||||
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
|
||||
|
||||
# Validate artifact file checksums too
|
||||
for name, body in artifact_files.items():
|
||||
expected = checksums.get(name)
|
||||
actual = _sha256(body)
|
||||
if expected != actual:
|
||||
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
|
||||
|
||||
payload: dict[str, Any] = {}
|
||||
for name, body in raw.items():
|
||||
if name == "checksums.json":
|
||||
@@ -171,6 +186,11 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
payload["work_journal_entries.json"] = []
|
||||
missing_optional.add("work_journal_entries.json")
|
||||
|
||||
# Backward compatibility: old archives have no document artifacts.
|
||||
if "document_artifacts.json" not in payload:
|
||||
payload["document_artifacts.json"] = []
|
||||
missing_optional.add("document_artifacts.json")
|
||||
|
||||
manifest = payload.get("manifest.json")
|
||||
if not isinstance(manifest, dict):
|
||||
raise ProjectImportError("manifest.json: ожидается объект")
|
||||
@@ -187,7 +207,8 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
if not isinstance(payload.get(name), list):
|
||||
raise ProjectImportError(f"{name}: ожидается массив")
|
||||
|
||||
return {"payload": payload, "manifest": manifest, "missing_optional": missing_optional}
|
||||
return {"payload": payload, "manifest": manifest, "missing_optional": missing_optional,
|
||||
"artifact_files": artifact_files}
|
||||
|
||||
|
||||
def _validate_records(
|
||||
@@ -299,6 +320,48 @@ def _validate_records(
|
||||
if _parse_decimal(row.get("amount"), "amount", required=True) <= 0:
|
||||
raise ProjectImportError("payment_allocations: amount должен быть > 0")
|
||||
|
||||
# Validate document_artifacts.json
|
||||
ks2_ids = {r["export_id"] for r in payload["ks2.json"]}
|
||||
ks3_ids = {r["export_id"] for r in payload["ks3.json"]}
|
||||
ks2_status = {r["export_id"]: r["status"] for r in payload["ks2.json"]}
|
||||
ks3_status = {r["export_id"]: r["status"] for r in payload["ks3.json"]}
|
||||
allowed_doc_ids = ks2_ids | ks3_ids
|
||||
allowed_statuses = {"issued", "cancelled"}
|
||||
art_required = ("export_id", "document_type", "document_export_id", "format",
|
||||
"template_type", "template_version", "content_hash", "input_hash",
|
||||
"archive_path")
|
||||
for idx, row in enumerate(payload.get("document_artifacts.json", []), start=1):
|
||||
for field in art_required:
|
||||
if field not in row:
|
||||
raise ProjectImportError(f"document_artifacts[{idx}]: нет поля {field}")
|
||||
if row["document_type"] not in ("KS2", "KS3"):
|
||||
raise ProjectImportError(f"document_artifacts[{idx}]: недопустимый document_type")
|
||||
if row["format"] not in ("xlsx", "docx"):
|
||||
raise ProjectImportError(f"document_artifacts[{idx}]: недопустимый format")
|
||||
if not isinstance(row["template_version"], int):
|
||||
raise ProjectImportError(f"document_artifacts[{idx}]: template_version должен быть числом")
|
||||
for hf in ("content_hash", "input_hash"):
|
||||
h = row[hf]
|
||||
if not isinstance(h, str) or len(h) != 64:
|
||||
raise ProjectImportError(f"document_artifacts[{idx}]: {hf} должен быть SHA-256 (64 символа)")
|
||||
# document_export_id must reference issued/cancelled KS-2/KS-3
|
||||
deid = row["document_export_id"]
|
||||
if deid not in allowed_doc_ids:
|
||||
raise ProjectImportError(f"document_artifacts[{idx}]: неизвестный document_export_id {deid!r}")
|
||||
status = ks2_status.get(deid) or ks3_status.get(deid)
|
||||
if status not in allowed_statuses:
|
||||
raise ProjectImportError(
|
||||
f"document_artifacts[{idx}]: artifact может относиться только к issued/cancelled документу"
|
||||
)
|
||||
# archive_path must be safe and under artifacts/
|
||||
ap = row["archive_path"].replace("\\", "/")
|
||||
if not ap.startswith("artifacts/") or ".." in ap.split("/") or ap.startswith("/"):
|
||||
raise ProjectImportError(f"document_artifacts[{idx}]: небезопасный archive_path")
|
||||
if row["format"] == "xlsx" and not ap.endswith(".xlsx"):
|
||||
raise ProjectImportError(f"document_artifacts[{idx}]: расширение не соответствует format")
|
||||
if row["format"] == "docx" and not ap.endswith(".docx"):
|
||||
raise ProjectImportError(f"document_artifacts[{idx}]: расширение не соответствует format")
|
||||
|
||||
# Internal export_id references
|
||||
def has(name: str, eid: str) -> bool:
|
||||
return eid in export_ids.get(name, set())
|
||||
@@ -376,18 +439,41 @@ def validate_archive(data: bytes) -> dict[str, Any]:
|
||||
result = _read_archive(data)
|
||||
payload = result["payload"]
|
||||
manifest = result["manifest"]
|
||||
artifact_files = result.get("artifact_files", {})
|
||||
_validate_records(payload, manifest, result.get("missing_optional"))
|
||||
|
||||
# Validate artifact files against document_artifacts.json
|
||||
art_rows = payload.get("document_artifacts.json", [])
|
||||
art_paths = {r["archive_path"] for r in art_rows}
|
||||
for row in art_rows:
|
||||
ap = row["archive_path"]
|
||||
if ap not in artifact_files:
|
||||
raise ProjectImportError(f"Artifact file missing in archive: {ap}")
|
||||
from app.services.document_artifact_service import compute_content_hash
|
||||
actual = compute_content_hash(artifact_files[ap])
|
||||
if actual != row["content_hash"]:
|
||||
raise ProjectImportError(f"Artifact hash mismatch for {ap}")
|
||||
# No orphan artifact references
|
||||
for ap in artifact_files:
|
||||
if ap not in art_paths:
|
||||
raise ProjectImportError(f"Orphan artifact file in archive: {ap}")
|
||||
|
||||
counts = dict(manifest.get("counts") or {})
|
||||
if "work_journal_entries.json" in result.get("missing_optional", set()):
|
||||
counts["work_journal_entries"] = 0
|
||||
else:
|
||||
counts.setdefault("work_journal_entries", len(payload.get("work_journal_entries.json", [])))
|
||||
if "document_artifacts.json" in result.get("missing_optional", set()):
|
||||
counts["document_artifacts"] = 0
|
||||
else:
|
||||
counts.setdefault("document_artifacts", len(art_rows))
|
||||
return {
|
||||
"manifest": manifest,
|
||||
"project_name": payload["project.json"].get("name"),
|
||||
"project": payload["project.json"],
|
||||
"counts": counts,
|
||||
"payload": payload,
|
||||
"artifact_files": artifact_files,
|
||||
}
|
||||
|
||||
|
||||
@@ -645,6 +731,55 @@ def _import_entities(db: Session, payload: dict[str, Any]) -> Project:
|
||||
db.flush()
|
||||
ids[row["export_id"]] = obj.id
|
||||
|
||||
# Restore document artifacts (official issued/cancelled files)
|
||||
created_artifact_paths: list = []
|
||||
try:
|
||||
from app.services.document_artifact_service import build_storage_key, resolve_storage_path
|
||||
from app.config import document_storage_root
|
||||
|
||||
artifact_files = payload.get("__artifact_files__", {})
|
||||
for row in payload.get("document_artifacts.json", []):
|
||||
doc_type = row["document_type"]
|
||||
new_doc_id = _require_mapping(row["document_export_id"], ids, "document_export_id")
|
||||
ext = row["format"]
|
||||
storage_key = build_storage_key(
|
||||
project.id, doc_type, new_doc_id,
|
||||
row["template_type"], row["template_version"], ext,
|
||||
)
|
||||
file_bytes = artifact_files.get(row["archive_path"])
|
||||
if file_bytes is None:
|
||||
raise ProjectImportError(f"Artifact file missing in archive: {row['archive_path']}")
|
||||
dest = resolve_storage_path(storage_key)
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(file_bytes)
|
||||
created_artifact_paths.append(dest)
|
||||
|
||||
art = DocumentArtifact(
|
||||
project_id=project.id,
|
||||
document_type=doc_type,
|
||||
document_id=new_doc_id,
|
||||
format=ext,
|
||||
storage_key=storage_key,
|
||||
template_type=row["template_type"],
|
||||
template_version=int(row["template_version"]),
|
||||
content_hash=row["content_hash"],
|
||||
input_hash=row["input_hash"],
|
||||
is_current=bool(row.get("is_current", True)),
|
||||
generated_at=_parse_datetime(row.get("generated_at"), "generated_at"),
|
||||
)
|
||||
db.add(art)
|
||||
db.flush()
|
||||
ids[row["export_id"]] = art.id
|
||||
except Exception:
|
||||
# Compensating cleanup: remove files created by this attempt
|
||||
for p in created_artifact_paths:
|
||||
try:
|
||||
if p.is_file():
|
||||
p.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
db.flush()
|
||||
return project
|
||||
|
||||
@@ -653,6 +788,7 @@ def import_project(db: Session, data: bytes) -> Project:
|
||||
"""Validate archive then create a new project atomically."""
|
||||
preview = validate_archive(data)
|
||||
payload = preview["payload"]
|
||||
payload["__artifact_files__"] = preview.get("artifact_files", {})
|
||||
try:
|
||||
project = _import_entities(db, payload)
|
||||
db.commit()
|
||||
|
||||
Reference in New Issue
Block a user