fix: include work journal in project export/import with old-archive compatibility
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user