fix: include work journal in project export/import with old-archive compatibility

This commit is contained in:
Арсентьев Александр
2026-09-28 17:45:39 +03:00
parent b5fa601e93
commit fac2816622
7 changed files with 594 additions and 8 deletions
+34 -1
View File
@@ -19,6 +19,7 @@ from app.models.ks2 import KS2, KS2Item, KS2ItemSource
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
FORMAT_NAME = "work_volume_tracker"
FORMAT_VERSION = 1
@@ -44,6 +45,10 @@ REQUIRED_FILES = (
"checksums.json",
)
# Old Task 025 archives may lack this file; import treats it as an empty journal.
OPTIONAL_FILES = ("work_journal_entries.json",)
EXPORT_FILES = REQUIRED_FILES[:-1] + OPTIONAL_FILES + ("checksums.json",)
class ProjectExportError(RuntimeError):
"""Raised when the project cannot be exported safely."""
@@ -173,6 +178,12 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
.order_by(PaymentAllocation.id)
.all()
)
work_journal_entries = (
db.query(WorkJournalEntry)
.filter(WorkJournalEntry.project_id == project_id)
.order_by(WorkJournalEntry.id)
.all()
)
return {
"project": project,
@@ -191,6 +202,7 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
"ks3_ks2": ks3_ks2,
"payments": payments,
"payment_allocations": payment_allocations,
"work_journal_entries": work_journal_entries,
}
@@ -292,6 +304,9 @@ def _validate_graph(graph: dict[str, Any]) -> None:
errors.append(f"payment_allocation:{a.id} references missing payment")
if a.ks3_id not in ks3_ids:
errors.append(f"payment_allocation:{a.id} references missing ks3")
for entry in graph.get("work_journal_entries", []):
if entry.project_id != pid:
errors.append(f"work_journal_entry:{entry.id} belongs to another project")
if errors:
raise ProjectExportError(
@@ -323,6 +338,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"ks3_ks2": _key_map(graph["ks3_ks2"], "ks3_ks2"),
"payment": _key_map(graph["payments"], "payment"),
"payment_allocation": _key_map(graph["payment_allocations"], "payment_allocation"),
"work_journal_entry": _key_map(graph.get("work_journal_entries", []), "work_journal_entry"),
}
def ref(kind: str, value: int | None) -> str | None:
@@ -584,6 +600,21 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
)
for a in graph["payment_allocations"]
]
work_journal_entries = [
record(
"work_journal_entry",
e,
{
"type": e.type,
"text": e.text,
"status": e.status,
"due_date": _iso(e.due_date),
"created_at": _iso(e.created_at),
"updated_at": _iso(e.updated_at),
},
)
for e in graph.get("work_journal_entries", [])
]
counts = {
"boq_documents": len(boq_documents),
@@ -601,6 +632,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"ks3_ks2": len(ks3_ks2),
"payments": len(payments),
"payment_allocations": len(payment_allocations),
"work_journal_entries": len(work_journal_entries),
}
manifest = {
"format": FORMAT_NAME,
@@ -629,6 +661,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"ks3_ks2.json": ks3_ks2,
"payments.json": payments,
"payment_allocations.json": payment_allocations,
"work_journal_entries.json": work_journal_entries,
}
@@ -640,7 +673,7 @@ def build_archive(files: dict[str, Any]) -> tuple[bytes, str]:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for name in REQUIRED_FILES:
for name in EXPORT_FILES:
if name not in parts:
raise ProjectExportError(f"В архиве отсутствует обязательный файл {name}")
zf.writestr(name, parts[name])
+56 -6
View File
@@ -18,9 +18,11 @@ from app.models.ks2 import KS2, KS2Item, KS2ItemSource
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.exporters.project_export import (
FORMAT_NAME,
FORMAT_VERSION,
OPTIONAL_FILES,
REQUIRED_FILES,
ProjectExportError,
)
@@ -46,6 +48,7 @@ _LIST_FILES = (
"ks3_ks2.json",
"payments.json",
"payment_allocations.json",
"work_journal_entries.json",
)
_ALLOWED_AGREEMENT_STATUS = {"draft", "approved"}
@@ -71,6 +74,7 @@ _REQUIRED_FIELDS: dict[str, tuple[str, ...]] = {
"ks3_ks2.json": ("export_id", "ks3_export_id", "ks2_export_id"),
"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"),
}
@@ -134,7 +138,8 @@ def _read_archive(data: bytes) -> dict[str, Any]:
if missing:
raise ProjectImportError(f"В архиве отсутствуют файлы: {', '.join(missing)}")
raw: dict[str, bytes] = {n: zf.read(n) for n in REQUIRED_FILES}
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}
try:
checksums = json.loads(raw["checksums.json"].decode("utf-8"))
@@ -160,6 +165,12 @@ def _read_archive(data: bytes) -> dict[str, Any]:
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise ProjectImportError(f"{name}: некорректный JSON") from exc
# Backward compatibility: old Task 025 archives have no work journal file.
missing_optional = set()
if "work_journal_entries.json" not in payload:
payload["work_journal_entries.json"] = []
missing_optional.add("work_journal_entries.json")
manifest = payload.get("manifest.json")
if not isinstance(manifest, dict):
raise ProjectImportError("manifest.json: ожидается объект")
@@ -176,11 +187,16 @@ def _read_archive(data: bytes) -> dict[str, Any]:
if not isinstance(payload.get(name), list):
raise ProjectImportError(f"{name}: ожидается массив")
return {"payload": payload, "manifest": manifest}
return {"payload": payload, "manifest": manifest, "missing_optional": missing_optional}
def _validate_records(payload: dict[str, Any], manifest: dict[str, Any]) -> None:
def _validate_records(
payload: dict[str, Any],
manifest: dict[str, Any],
missing_optional: set[str] | None = None,
) -> None:
"""Validate required fields, types, statuses, and internal export_id links."""
missing_optional = missing_optional or set()
project = payload["project.json"]
for field in _REQUIRED_FIELDS["project.json"]:
if field not in project:
@@ -223,9 +239,24 @@ def _validate_records(payload: dict[str, Any], manifest: dict[str, Any]) -> None
"ks3_ks2.json": "ks3_ks2",
"payments.json": "payments",
"payment_allocations.json": "payment_allocations",
"work_journal_entries.json": "work_journal_entries",
}
for name, key in name_to_key.items():
if key in counts and counts[key] != len(payload[name]):
# Old manifests may omit work_journal_entries — treat as 0.
if key == "work_journal_entries":
if name in missing_optional:
continue
expected = counts.get(key, 0)
actual = len(payload.get(name, []))
if expected != actual:
raise ProjectImportError(
f"Количество записей {key} не совпадает с manifest: "
f"{expected} != {actual}"
)
continue
if key not in counts:
continue
if counts[key] != len(payload[name]):
raise ProjectImportError(
f"Количество записей {key} не совпадает с manifest: "
f"{counts[key]} != {len(payload[name])}"
@@ -345,12 +376,17 @@ def validate_archive(data: bytes) -> dict[str, Any]:
result = _read_archive(data)
payload = result["payload"]
manifest = result["manifest"]
_validate_records(payload, manifest)
_validate_records(payload, manifest, result.get("missing_optional"))
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", [])))
return {
"manifest": manifest,
"project_name": payload["project.json"].get("name"),
"project": payload["project.json"],
"counts": manifest.get("counts", {}),
"counts": counts,
"payload": payload,
}
@@ -595,6 +631,20 @@ def _import_entities(db: Session, payload: dict[str, Any]) -> Project:
db.flush()
ids[row["export_id"]] = obj.id
for row in payload.get("work_journal_entries.json", []):
obj = WorkJournalEntry(
project_id=project.id,
type=row["type"],
text=row["text"],
status=row.get("status"),
due_date=_parse_date(row.get("due_date"), "due_date"),
created_at=_parse_datetime(row.get("created_at"), "created_at"),
updated_at=_parse_datetime(row.get("updated_at"), "updated_at"),
)
db.add(obj)
db.flush()
ids[row["export_id"]] = obj.id
db.flush()
return project