feat: add photos to daily reports
This commit is contained in:
@@ -51,6 +51,7 @@ _LIST_FILES = (
|
||||
"payment_allocations.json",
|
||||
"work_journal_entries.json",
|
||||
"document_artifacts.json",
|
||||
"daily_report_photos.json",
|
||||
)
|
||||
|
||||
_ALLOWED_AGREEMENT_STATUS = {"draft", "approved", "cancelled"}
|
||||
@@ -78,6 +79,7 @@ _REQUIRED_FIELDS: dict[str, tuple[str, ...]] = {
|
||||
"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"),
|
||||
"daily_report_photos.json": ("export_id", "daily_report_export_id", "content_type", "file_size", "content_hash", "archive_path"),
|
||||
}
|
||||
|
||||
|
||||
@@ -148,6 +150,11 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
for name in names:
|
||||
if name.startswith("artifacts/") and not name.endswith("/"):
|
||||
artifact_files[name] = zf.read(name)
|
||||
# Daily Report photo files (any path under photos/)
|
||||
photo_files: dict[str, bytes] = {}
|
||||
for name in names:
|
||||
if name.startswith("photos/") and not name.endswith("/"):
|
||||
photo_files[name] = zf.read(name)
|
||||
|
||||
try:
|
||||
checksums = json.loads(raw["checksums.json"].decode("utf-8"))
|
||||
@@ -171,6 +178,13 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
if expected != actual:
|
||||
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
|
||||
|
||||
# Validate photo file checksums too
|
||||
for name, body in photo_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":
|
||||
@@ -191,6 +205,11 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
payload["document_artifacts.json"] = []
|
||||
missing_optional.add("document_artifacts.json")
|
||||
|
||||
# Backward compatibility: old archives have no Daily Report photos.
|
||||
if "daily_report_photos.json" not in payload:
|
||||
payload["daily_report_photos.json"] = []
|
||||
missing_optional.add("daily_report_photos.json")
|
||||
|
||||
manifest = payload.get("manifest.json")
|
||||
if not isinstance(manifest, dict):
|
||||
raise ProjectImportError("manifest.json: ожидается объект")
|
||||
@@ -208,7 +227,7 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
raise ProjectImportError(f"{name}: ожидается массив")
|
||||
|
||||
return {"payload": payload, "manifest": manifest, "missing_optional": missing_optional,
|
||||
"artifact_files": artifact_files}
|
||||
"artifact_files": artifact_files, "photo_files": photo_files}
|
||||
|
||||
|
||||
def _validate_records(
|
||||
@@ -397,6 +416,17 @@ def _validate_records(
|
||||
raise ProjectImportError("daily_report_items: битая ссылка на daily_report")
|
||||
if not has("work_items.json", row["work_item_export_id"]):
|
||||
raise ProjectImportError("daily_report_items: битая ссылка на work_item")
|
||||
for idx, row in enumerate(payload.get("daily_report_photos.json", []), 1):
|
||||
for field in _REQUIRED_FIELDS["daily_report_photos.json"]:
|
||||
if field not in row:
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: нет поля {field}")
|
||||
if not has("daily_reports.json", row["daily_report_export_id"]):
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: битая ссылка на daily_report")
|
||||
if not isinstance(row["file_size"], int) or row["file_size"] <= 0:
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: file_size должен быть положительным числом")
|
||||
h = row["content_hash"]
|
||||
if not isinstance(h, str) or len(h) != 64:
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: content_hash должен быть SHA-256 (64 символа)")
|
||||
for row in payload["ks2_items.json"]:
|
||||
if not has("ks2.json", row["ks2_export_id"]):
|
||||
raise ProjectImportError("ks2_items: битая ссылка на ks2")
|
||||
@@ -458,6 +488,35 @@ def validate_archive(data: bytes) -> dict[str, Any]:
|
||||
if ap not in art_paths:
|
||||
raise ProjectImportError(f"Orphan artifact file in archive: {ap}")
|
||||
|
||||
# Validate photo files against daily_report_photos.json
|
||||
photo_files = result.get("photo_files", {})
|
||||
photo_rows = payload.get("daily_report_photos.json", [])
|
||||
photo_paths = {r["archive_path"] for r in photo_rows}
|
||||
from app.services.daily_report_photo_service import (
|
||||
ALLOWED_CONTENT_TYPES,
|
||||
MAX_PHOTO_BYTES,
|
||||
compute_content_hash as photo_hash,
|
||||
)
|
||||
for idx, row in enumerate(photo_rows, 1):
|
||||
ap = row["archive_path"]
|
||||
if not isinstance(ap, str) or not ap.startswith("photos/") or ".." in ap.split("/") or ap.startswith("/"):
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: небезопасный archive_path")
|
||||
if ap not in photo_files:
|
||||
raise ProjectImportError(f"Photo file missing in archive: {ap}")
|
||||
body = photo_files[ap]
|
||||
if len(body) > MAX_PHOTO_BYTES:
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: файл превышает лимит размера")
|
||||
if photo_hash(body) != row["content_hash"]:
|
||||
raise ProjectImportError(f"Photo hash mismatch for {ap}")
|
||||
if int(row.get("file_size") or 0) != len(body):
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: file_size не совпадает с содержимым")
|
||||
if row["content_type"] not in ALLOWED_CONTENT_TYPES:
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: недопустимый content_type")
|
||||
# No orphan photo files
|
||||
for ap in photo_files:
|
||||
if ap not in photo_paths:
|
||||
raise ProjectImportError(f"Orphan photo 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
|
||||
@@ -467,6 +526,10 @@ def validate_archive(data: bytes) -> dict[str, Any]:
|
||||
counts["document_artifacts"] = 0
|
||||
else:
|
||||
counts.setdefault("document_artifacts", len(art_rows))
|
||||
if "daily_report_photos.json" in result.get("missing_optional", set()):
|
||||
counts["daily_report_photos"] = 0
|
||||
else:
|
||||
counts.setdefault("daily_report_photos", len(photo_rows))
|
||||
return {
|
||||
"manifest": manifest,
|
||||
"project_name": payload["project.json"].get("name"),
|
||||
@@ -474,6 +537,7 @@ def validate_archive(data: bytes) -> dict[str, Any]:
|
||||
"counts": counts,
|
||||
"payload": payload,
|
||||
"artifact_files": artifact_files,
|
||||
"photo_files": photo_files,
|
||||
}
|
||||
|
||||
|
||||
@@ -790,6 +854,58 @@ def _import_entities(db: Session, payload: dict[str, Any]) -> Project:
|
||||
pass
|
||||
raise
|
||||
|
||||
# Restore Daily Report photos (primary report attachments)
|
||||
created_photo_paths: list = []
|
||||
try:
|
||||
from app.services.daily_report_photo_service import (
|
||||
build_photo_storage_key,
|
||||
resolve_photo_path,
|
||||
)
|
||||
|
||||
photo_files = payload.get("__photo_files__", {})
|
||||
for row in payload.get("daily_report_photos.json", []):
|
||||
new_report_id = _require_mapping(
|
||||
row["daily_report_export_id"], ids, "daily_report_export_id"
|
||||
)
|
||||
# Extension comes from validated content_type, never from the archive name.
|
||||
ext_by_type = {"image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp"}
|
||||
ext = ext_by_type[row["content_type"]]
|
||||
storage_key = build_photo_storage_key(
|
||||
project.id, new_report_id, ext,
|
||||
)
|
||||
file_bytes = photo_files.get(row["archive_path"])
|
||||
if file_bytes is None:
|
||||
raise ProjectImportError(
|
||||
f"Photo file missing in archive: {row['archive_path']}"
|
||||
)
|
||||
dest = resolve_photo_path(storage_key)
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(file_bytes)
|
||||
created_photo_paths.append(dest)
|
||||
|
||||
from app.models.daily_report_photo import DailyReportPhoto
|
||||
photo = DailyReportPhoto(
|
||||
project_id=project.id,
|
||||
daily_report_id=new_report_id,
|
||||
storage_key=storage_key,
|
||||
original_name=row.get("original_name"),
|
||||
content_type=row["content_type"],
|
||||
file_size=int(row["file_size"]),
|
||||
content_hash=row["content_hash"],
|
||||
sort_order=int(row.get("sort_order") or 0),
|
||||
)
|
||||
db.add(photo)
|
||||
db.flush()
|
||||
ids[row["export_id"]] = photo.id
|
||||
except Exception:
|
||||
for p in created_photo_paths:
|
||||
try:
|
||||
if p.is_file():
|
||||
p.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
db.flush()
|
||||
return project
|
||||
|
||||
@@ -799,6 +915,7 @@ def import_project(db: Session, data: bytes) -> Project:
|
||||
preview = validate_archive(data)
|
||||
payload = preview["payload"]
|
||||
payload["__artifact_files__"] = preview.get("artifact_files", {})
|
||||
payload["__photo_files__"] = preview.get("photo_files", {})
|
||||
try:
|
||||
project = _import_entities(db, payload)
|
||||
db.commit()
|
||||
|
||||
Reference in New Issue
Block a user