feat: add photos to daily reports

This commit is contained in:
Арсентьев Александр
2026-10-15 14:42:04 +03:00
parent 1af2a70406
commit 3a3e481750
14 changed files with 1765 additions and 20 deletions
+56 -2
View File
@@ -15,6 +15,7 @@ from sqlalchemy.orm import Session, joinedload
from app.models.agreement import Agreement, AgreementItem
from app.models.boq import BoqDocument, Section, System, WorkItem
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.daily_report_photo import DailyReportPhoto
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
from app.models.ks3 import KS3, KS3KS2
from app.models.payment import Payment, PaymentAllocation
@@ -46,8 +47,12 @@ 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", "document_artifacts.json")
# Old Task 025 archives may lack these files; import treats them as empty.
OPTIONAL_FILES = (
"work_journal_entries.json",
"document_artifacts.json",
"daily_report_photos.json",
)
EXPORT_FILES = REQUIRED_FILES[:-1] + OPTIONAL_FILES + ("checksums.json",)
@@ -198,6 +203,13 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
.order_by(DocumentArtifact.id)
.all()
)
# Daily Report photos belong to the primary report and travel with it.
daily_report_photos = (
db.query(DailyReportPhoto)
.filter(DailyReportPhoto.project_id == project_id)
.order_by(DailyReportPhoto.id)
.all()
)
return {
"project": project,
@@ -209,6 +221,7 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
"agreement_items": agreement_items,
"daily_reports": daily_reports,
"daily_report_items": daily_report_items,
"daily_report_photos": daily_report_photos,
"ks2": ks2_docs,
"ks2_items": ks2_items,
"ks2_item_sources": ks2_item_sources,
@@ -291,6 +304,11 @@ def _validate_graph(graph: dict[str, Any]) -> None:
errors.append(f"daily_report_item:{i.id} references missing daily_report")
if i.work_item_id not in work_item_ids:
errors.append(f"daily_report_item:{i.id} references missing work_item")
for p in graph.get("daily_report_photos", []):
if p.daily_report_id not in report_ids:
errors.append(f"daily_report_photo:{p.id} references missing daily_report")
if p.project_id != pid:
errors.append(f"daily_report_photo:{p.id} belongs to another project")
for k in graph["ks2"]:
if k.project_id != pid:
errors.append(f"ks2:{k.id} belongs to another project")
@@ -347,6 +365,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"agreement_item": _key_map(graph["agreement_items"], "agreement_item"),
"daily_report": _key_map(graph["daily_reports"], "daily_report"),
"daily_report_item": _key_map(graph["daily_report_items"], "daily_report_item"),
"daily_report_photo": _key_map(graph.get("daily_report_photos", []), "daily_report_photo"),
"ks2": _key_map(graph["ks2"], "ks2"),
"ks2_item": _key_map(graph["ks2_items"], "ks2_item"),
"ks2_item_source": _key_map(graph["ks2_item_sources"], "ks2_item_source"),
@@ -526,6 +545,38 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
)
for i in graph["daily_report_items"]
]
daily_report_photo_records = []
photo_blobs: dict[str, bytes] = {}
for photo in graph.get("daily_report_photos", []):
photo_export_id = ref("daily_report", photo.daily_report_id)
if photo_export_id is None:
raise ProjectExportError(
f"Photo {photo.id} references unknown DailyReport {photo.daily_report_id}"
)
try:
from app.services.daily_report_photo_service import (
photo_file_bytes,
)
file_bytes = photo_file_bytes(photo)
except Exception as exc:
raise ProjectExportError(
f"Photo file missing for daily_report_photo:{photo.id} "
f"({photo.storage_key})"
) from exc
archive_path = f"photos/{photo_export_id.replace(':', '_')}/{photo.id:08d}.bin"
photo_blobs[archive_path] = file_bytes
daily_report_photo_records.append({
"export_id": f"daily_report_photo:{photo.id:08d}",
"source_id": photo.id,
"daily_report_export_id": photo_export_id,
"original_name": photo.original_name,
"content_type": photo.content_type,
"file_size": photo.file_size,
"content_hash": photo.content_hash,
"sort_order": photo.sort_order,
"created_at": _iso(photo.created_at),
"archive_path": archive_path,
})
ks2 = [
record(
"ks2",
@@ -710,6 +761,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"agreement_items": len(agreement_items),
"daily_reports": len(daily_reports),
"daily_report_items": len(daily_report_items),
"daily_report_photos": len(daily_report_photo_records),
"ks2": len(ks2),
"ks2_items": len(ks2_items),
"ks2_item_sources": len(ks2_item_sources),
@@ -740,6 +792,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"agreement_items.json": agreement_items,
"daily_reports.json": daily_reports,
"daily_report_items.json": daily_report_items,
"daily_report_photos.json": daily_report_photo_records,
"ks2.json": ks2,
"ks2_items.json": ks2_items,
"ks2_item_sources.json": ks2_item_sources,
@@ -750,6 +803,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"work_journal_entries.json": work_journal_entries,
"document_artifacts.json": document_artifacts_records,
}
artifact_blobs.update(photo_blobs)
return {**files, "__artifact_blobs__": artifact_blobs}
+118 -1
View File
@@ -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()