feat: add photos to daily reports
This commit is contained in:
@@ -14,6 +14,7 @@ BOQ_DOCUMENT_REQUISITES_MIGRATION = "20260928_boq_document_requisites"
|
|||||||
DOCUMENT_ARTIFACTS_MIGRATION = "20260928_document_artifacts"
|
DOCUMENT_ARTIFACTS_MIGRATION = "20260928_document_artifacts"
|
||||||
AGREEMENT_STATUS_CANCELLED_MIGRATION = "20260930_agreement_status_cancelled"
|
AGREEMENT_STATUS_CANCELLED_MIGRATION = "20260930_agreement_status_cancelled"
|
||||||
PROJECT_REQUISITES_MIGRATION = "20260930_project_requisites"
|
PROJECT_REQUISITES_MIGRATION = "20260930_project_requisites"
|
||||||
|
DAILY_REPORT_PHOTOS_MIGRATION = "20261015_daily_report_photos"
|
||||||
|
|
||||||
|
|
||||||
def run_migrations(engine):
|
def run_migrations(engine):
|
||||||
@@ -308,6 +309,32 @@ def run_migrations(engine):
|
|||||||
)
|
)
|
||||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
(PROJECT_REQUISITES_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
(PROJECT_REQUISITES_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
|
if DAILY_REPORT_PHOTOS_MIGRATION not in applied:
|
||||||
|
connection.execute("""CREATE TABLE IF NOT EXISTS daily_report_photos (
|
||||||
|
id INTEGER NOT NULL PRIMARY KEY,
|
||||||
|
project_id INTEGER NOT NULL REFERENCES projects(id),
|
||||||
|
daily_report_id INTEGER NOT NULL REFERENCES daily_reports(id),
|
||||||
|
storage_key VARCHAR NOT NULL,
|
||||||
|
original_name VARCHAR,
|
||||||
|
content_type VARCHAR(100) NOT NULL,
|
||||||
|
file_size INTEGER NOT NULL,
|
||||||
|
content_hash VARCHAR(64) NOT NULL,
|
||||||
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)""")
|
||||||
|
connection.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_daily_report_photos_id ON daily_report_photos (id)"
|
||||||
|
)
|
||||||
|
connection.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_daily_report_photos_project_id "
|
||||||
|
"ON daily_report_photos (project_id)"
|
||||||
|
)
|
||||||
|
connection.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_daily_report_photos_report_id "
|
||||||
|
"ON daily_report_photos (daily_report_id)"
|
||||||
|
)
|
||||||
|
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||||
|
(DAILY_REPORT_PHOTOS_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||||
violations = connection.execute("PRAGMA foreign_key_check").fetchall()
|
violations = connection.execute("PRAGMA foreign_key_check").fetchall()
|
||||||
if violations:
|
if violations:
|
||||||
raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}")
|
raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}")
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from sqlalchemy.orm import Session, joinedload
|
|||||||
from app.models.agreement import Agreement, AgreementItem
|
from app.models.agreement import Agreement, AgreementItem
|
||||||
from app.models.boq import BoqDocument, Section, System, WorkItem
|
from app.models.boq import BoqDocument, Section, System, WorkItem
|
||||||
from app.models.daily_report import DailyReport, DailyReportItem
|
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.ks2 import KS2, KS2Item, KS2ItemSource
|
||||||
from app.models.ks3 import KS3, KS3KS2
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
from app.models.payment import Payment, PaymentAllocation
|
from app.models.payment import Payment, PaymentAllocation
|
||||||
@@ -46,8 +47,12 @@ REQUIRED_FILES = (
|
|||||||
"checksums.json",
|
"checksums.json",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Old Task 025 archives may lack this file; import treats it as an empty journal.
|
# Old Task 025 archives may lack these files; import treats them as empty.
|
||||||
OPTIONAL_FILES = ("work_journal_entries.json", "document_artifacts.json")
|
OPTIONAL_FILES = (
|
||||||
|
"work_journal_entries.json",
|
||||||
|
"document_artifacts.json",
|
||||||
|
"daily_report_photos.json",
|
||||||
|
)
|
||||||
EXPORT_FILES = REQUIRED_FILES[:-1] + OPTIONAL_FILES + ("checksums.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)
|
.order_by(DocumentArtifact.id)
|
||||||
.all()
|
.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 {
|
return {
|
||||||
"project": project,
|
"project": project,
|
||||||
@@ -209,6 +221,7 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
|
|||||||
"agreement_items": agreement_items,
|
"agreement_items": agreement_items,
|
||||||
"daily_reports": daily_reports,
|
"daily_reports": daily_reports,
|
||||||
"daily_report_items": daily_report_items,
|
"daily_report_items": daily_report_items,
|
||||||
|
"daily_report_photos": daily_report_photos,
|
||||||
"ks2": ks2_docs,
|
"ks2": ks2_docs,
|
||||||
"ks2_items": ks2_items,
|
"ks2_items": ks2_items,
|
||||||
"ks2_item_sources": ks2_item_sources,
|
"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")
|
errors.append(f"daily_report_item:{i.id} references missing daily_report")
|
||||||
if i.work_item_id not in work_item_ids:
|
if i.work_item_id not in work_item_ids:
|
||||||
errors.append(f"daily_report_item:{i.id} references missing work_item")
|
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"]:
|
for k in graph["ks2"]:
|
||||||
if k.project_id != pid:
|
if k.project_id != pid:
|
||||||
errors.append(f"ks2:{k.id} belongs to another project")
|
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"),
|
"agreement_item": _key_map(graph["agreement_items"], "agreement_item"),
|
||||||
"daily_report": _key_map(graph["daily_reports"], "daily_report"),
|
"daily_report": _key_map(graph["daily_reports"], "daily_report"),
|
||||||
"daily_report_item": _key_map(graph["daily_report_items"], "daily_report_item"),
|
"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": _key_map(graph["ks2"], "ks2"),
|
||||||
"ks2_item": _key_map(graph["ks2_items"], "ks2_item"),
|
"ks2_item": _key_map(graph["ks2_items"], "ks2_item"),
|
||||||
"ks2_item_source": _key_map(graph["ks2_item_sources"], "ks2_item_source"),
|
"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"]
|
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 = [
|
ks2 = [
|
||||||
record(
|
record(
|
||||||
"ks2",
|
"ks2",
|
||||||
@@ -710,6 +761,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
|
|||||||
"agreement_items": len(agreement_items),
|
"agreement_items": len(agreement_items),
|
||||||
"daily_reports": len(daily_reports),
|
"daily_reports": len(daily_reports),
|
||||||
"daily_report_items": len(daily_report_items),
|
"daily_report_items": len(daily_report_items),
|
||||||
|
"daily_report_photos": len(daily_report_photo_records),
|
||||||
"ks2": len(ks2),
|
"ks2": len(ks2),
|
||||||
"ks2_items": len(ks2_items),
|
"ks2_items": len(ks2_items),
|
||||||
"ks2_item_sources": len(ks2_item_sources),
|
"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,
|
"agreement_items.json": agreement_items,
|
||||||
"daily_reports.json": daily_reports,
|
"daily_reports.json": daily_reports,
|
||||||
"daily_report_items.json": daily_report_items,
|
"daily_report_items.json": daily_report_items,
|
||||||
|
"daily_report_photos.json": daily_report_photo_records,
|
||||||
"ks2.json": ks2,
|
"ks2.json": ks2,
|
||||||
"ks2_items.json": ks2_items,
|
"ks2_items.json": ks2_items,
|
||||||
"ks2_item_sources.json": ks2_item_sources,
|
"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,
|
"work_journal_entries.json": work_journal_entries,
|
||||||
"document_artifacts.json": document_artifacts_records,
|
"document_artifacts.json": document_artifacts_records,
|
||||||
}
|
}
|
||||||
|
artifact_blobs.update(photo_blobs)
|
||||||
return {**files, "__artifact_blobs__": artifact_blobs}
|
return {**files, "__artifact_blobs__": artifact_blobs}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ _LIST_FILES = (
|
|||||||
"payment_allocations.json",
|
"payment_allocations.json",
|
||||||
"work_journal_entries.json",
|
"work_journal_entries.json",
|
||||||
"document_artifacts.json",
|
"document_artifacts.json",
|
||||||
|
"daily_report_photos.json",
|
||||||
)
|
)
|
||||||
|
|
||||||
_ALLOWED_AGREEMENT_STATUS = {"draft", "approved", "cancelled"}
|
_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"),
|
"payment_allocations.json": ("export_id", "payment_export_id", "ks3_export_id", "amount"),
|
||||||
"work_journal_entries.json": ("export_id", "type", "text"),
|
"work_journal_entries.json": ("export_id", "type", "text"),
|
||||||
"document_artifacts.json": ("export_id", "document_type", "document_export_id", "format", "content_hash", "archive_path"),
|
"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:
|
for name in names:
|
||||||
if name.startswith("artifacts/") and not name.endswith("/"):
|
if name.startswith("artifacts/") and not name.endswith("/"):
|
||||||
artifact_files[name] = zf.read(name)
|
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:
|
try:
|
||||||
checksums = json.loads(raw["checksums.json"].decode("utf-8"))
|
checksums = json.loads(raw["checksums.json"].decode("utf-8"))
|
||||||
@@ -171,6 +178,13 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
|||||||
if expected != actual:
|
if expected != actual:
|
||||||
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
|
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] = {}
|
payload: dict[str, Any] = {}
|
||||||
for name, body in raw.items():
|
for name, body in raw.items():
|
||||||
if name == "checksums.json":
|
if name == "checksums.json":
|
||||||
@@ -191,6 +205,11 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
|||||||
payload["document_artifacts.json"] = []
|
payload["document_artifacts.json"] = []
|
||||||
missing_optional.add("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")
|
manifest = payload.get("manifest.json")
|
||||||
if not isinstance(manifest, dict):
|
if not isinstance(manifest, dict):
|
||||||
raise ProjectImportError("manifest.json: ожидается объект")
|
raise ProjectImportError("manifest.json: ожидается объект")
|
||||||
@@ -208,7 +227,7 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
|||||||
raise ProjectImportError(f"{name}: ожидается массив")
|
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}
|
"artifact_files": artifact_files, "photo_files": photo_files}
|
||||||
|
|
||||||
|
|
||||||
def _validate_records(
|
def _validate_records(
|
||||||
@@ -397,6 +416,17 @@ def _validate_records(
|
|||||||
raise ProjectImportError("daily_report_items: битая ссылка на daily_report")
|
raise ProjectImportError("daily_report_items: битая ссылка на daily_report")
|
||||||
if not has("work_items.json", row["work_item_export_id"]):
|
if not has("work_items.json", row["work_item_export_id"]):
|
||||||
raise ProjectImportError("daily_report_items: битая ссылка на work_item")
|
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"]:
|
for row in payload["ks2_items.json"]:
|
||||||
if not has("ks2.json", row["ks2_export_id"]):
|
if not has("ks2.json", row["ks2_export_id"]):
|
||||||
raise ProjectImportError("ks2_items: битая ссылка на ks2")
|
raise ProjectImportError("ks2_items: битая ссылка на ks2")
|
||||||
@@ -458,6 +488,35 @@ def validate_archive(data: bytes) -> dict[str, Any]:
|
|||||||
if ap not in art_paths:
|
if ap not in art_paths:
|
||||||
raise ProjectImportError(f"Orphan artifact file in archive: {ap}")
|
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 {})
|
counts = dict(manifest.get("counts") or {})
|
||||||
if "work_journal_entries.json" in result.get("missing_optional", set()):
|
if "work_journal_entries.json" in result.get("missing_optional", set()):
|
||||||
counts["work_journal_entries"] = 0
|
counts["work_journal_entries"] = 0
|
||||||
@@ -467,6 +526,10 @@ def validate_archive(data: bytes) -> dict[str, Any]:
|
|||||||
counts["document_artifacts"] = 0
|
counts["document_artifacts"] = 0
|
||||||
else:
|
else:
|
||||||
counts.setdefault("document_artifacts", len(art_rows))
|
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 {
|
return {
|
||||||
"manifest": manifest,
|
"manifest": manifest,
|
||||||
"project_name": payload["project.json"].get("name"),
|
"project_name": payload["project.json"].get("name"),
|
||||||
@@ -474,6 +537,7 @@ def validate_archive(data: bytes) -> dict[str, Any]:
|
|||||||
"counts": counts,
|
"counts": counts,
|
||||||
"payload": payload,
|
"payload": payload,
|
||||||
"artifact_files": artifact_files,
|
"artifact_files": artifact_files,
|
||||||
|
"photo_files": photo_files,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -790,6 +854,58 @@ def _import_entities(db: Session, payload: dict[str, Any]) -> Project:
|
|||||||
pass
|
pass
|
||||||
raise
|
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()
|
db.flush()
|
||||||
return project
|
return project
|
||||||
|
|
||||||
@@ -799,6 +915,7 @@ def import_project(db: Session, data: bytes) -> Project:
|
|||||||
preview = validate_archive(data)
|
preview = validate_archive(data)
|
||||||
payload = preview["payload"]
|
payload = preview["payload"]
|
||||||
payload["__artifact_files__"] = preview.get("artifact_files", {})
|
payload["__artifact_files__"] = preview.get("artifact_files", {})
|
||||||
|
payload["__photo_files__"] = preview.get("photo_files", {})
|
||||||
try:
|
try:
|
||||||
project = _import_entities(db, payload)
|
project = _import_entities(db, payload)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ from app.routers import projects, boq as boq_router, daily_reports, agreements,
|
|||||||
# Import models to ensure they're registered
|
# Import models to ensure they're registered
|
||||||
from app.models import project as project_models, boq as boq_models
|
from app.models import project as project_models, boq as boq_models
|
||||||
from app.models import daily_report as daily_report_models
|
from app.models import daily_report as daily_report_models
|
||||||
|
from app.models import daily_report_photo as daily_report_photo_models
|
||||||
from app.models import work_journal as work_journal_models
|
from app.models import work_journal as work_journal_models
|
||||||
from app.models import agreement as agreement_models
|
from app.models import agreement as agreement_models
|
||||||
from app.models import ks2 as ks2_models
|
from app.models import ks2 as ks2_models
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ class DailyReport(Base):
|
|||||||
project = relationship("Project")
|
project = relationship("Project")
|
||||||
system = relationship("System")
|
system = relationship("System")
|
||||||
items = relationship("DailyReportItem", back_populates="report", cascade="all, delete-orphan")
|
items = relationship("DailyReportItem", back_populates="report", cascade="all, delete-orphan")
|
||||||
|
photos = relationship("DailyReportPhoto", back_populates="report", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
class DailyReportItem(Base):
|
class DailyReportItem(Base):
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Daily Report photo metadata.
|
||||||
|
|
||||||
|
Photo files live in the managed application storage, never in SQLite. This
|
||||||
|
table keeps metadata and the link to the owning Daily Report. Binary content
|
||||||
|
is not stored here.
|
||||||
|
|
||||||
|
Photos are attached to the Daily Report as a whole (REQ), not to individual
|
||||||
|
work positions.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import (
|
||||||
|
Column,
|
||||||
|
DateTime,
|
||||||
|
ForeignKey,
|
||||||
|
Integer,
|
||||||
|
String,
|
||||||
|
)
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
|
from app.database.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class DailyReportPhoto(Base):
|
||||||
|
__tablename__ = "daily_report_photos"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||||
|
daily_report_id = Column(
|
||||||
|
Integer, ForeignKey("daily_reports.id"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
# Relative path under DOCUMENT_STORAGE_ROOT. Never an absolute path or URL.
|
||||||
|
storage_key = Column(String, nullable=False)
|
||||||
|
# Display-only label from the uploader. Never used to build a path.
|
||||||
|
original_name = Column(String, nullable=True)
|
||||||
|
content_type = Column(String(100), nullable=False)
|
||||||
|
file_size = Column(Integer, nullable=False)
|
||||||
|
content_hash = Column(String(64), nullable=False)
|
||||||
|
sort_order = Column(Integer, nullable=False, default=0, server_default="0")
|
||||||
|
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||||
|
|
||||||
|
report = relationship("DailyReport", back_populates="photos")
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return (
|
||||||
|
f"<DailyReportPhoto(id={self.id}, report={self.daily_report_id}, "
|
||||||
|
f"size={self.file_size}, type={self.content_type!r})>"
|
||||||
|
)
|
||||||
+211
-13
@@ -1,8 +1,8 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
from decimal import Decimal, InvalidOperation
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
|
||||||
from fastapi.responses import RedirectResponse
|
from fastapi.responses import RedirectResponse, Response
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
@@ -20,6 +20,17 @@ from app.services.daily_report_service import (
|
|||||||
has_closed_volume,
|
has_closed_volume,
|
||||||
report_close_infos,
|
report_close_infos,
|
||||||
)
|
)
|
||||||
|
from app.services.daily_report_photo_service import (
|
||||||
|
DailyReportPhotoError,
|
||||||
|
PhotoNotFoundError,
|
||||||
|
PhotoValidationError,
|
||||||
|
MAX_PHOTOS_PER_REPORT,
|
||||||
|
MAX_PHOTO_BYTES,
|
||||||
|
ALLOWED_IMAGE_TYPES,
|
||||||
|
delete_photo,
|
||||||
|
persist_photos,
|
||||||
|
photo_file_bytes,
|
||||||
|
)
|
||||||
from app.services.effective_plan import build_effective_plan
|
from app.services.effective_plan import build_effective_plan
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -72,7 +83,8 @@ def _report_rows(db: Session, project_id: int, system_id: int | None, exclude_re
|
|||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
def _render_form(request, db, project_obj, system_id=None, report=None, errors=None):
|
def _render_form(request, db, project_obj, system_id=None, report=None, errors=None,
|
||||||
|
form_values=None, status_code=200):
|
||||||
effective = build_effective_plan(db, project_obj.id)["items"]
|
effective = build_effective_plan(db, project_obj.id)["items"]
|
||||||
token = "unclassified" if system_id == "unclassified" else (str(system_id) if system_id not in (None, "") else None)
|
token = "unclassified" if system_id == "unclassified" else (str(system_id) if system_id not in (None, "") else None)
|
||||||
unclassified = [row for row in effective if row.item.system_id is None]
|
unclassified = [row for row in effective if row.item.system_id is None]
|
||||||
@@ -103,16 +115,45 @@ def _render_form(request, db, project_obj, system_id=None, report=None, errors=N
|
|||||||
# system client-side and switching systems must not drop already-added rows.
|
# system client-side and switching systems must not drop already-added rows.
|
||||||
rows = _report_rows(db, project_obj.id, selected_id, report.id if report else None,
|
rows = _report_rows(db, project_obj.id, selected_id, report.id if report else None,
|
||||||
all_systems=True)
|
all_systems=True)
|
||||||
current = {line.work_item_id: line.completed_quantity for line in report.items} if report else {}
|
form_values = form_values or {}
|
||||||
|
if report is not None:
|
||||||
|
current = {line.work_item_id: line.completed_quantity for line in report.items}
|
||||||
|
else:
|
||||||
|
# Error recovery: re-show the quantities the user already submitted so a
|
||||||
|
# photo/quantity problem never wipes their in-progress report.
|
||||||
|
current = {}
|
||||||
|
for key, value in form_values.items():
|
||||||
|
if not key.startswith("quantity_"):
|
||||||
|
continue
|
||||||
|
raw = (value or "").strip()
|
||||||
|
if not raw:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
item_id = int(key.removeprefix("quantity_"))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
qty = Decimal(raw.replace(",", "."))
|
||||||
|
except (InvalidOperation, ValueError):
|
||||||
|
continue
|
||||||
|
if qty.is_finite() and qty > 0:
|
||||||
|
current[item_id] = qty
|
||||||
for row in rows:
|
for row in rows:
|
||||||
row["current_quantity"] = current.get(row["item"].id)
|
row["current_quantity"] = current.get(row["item"].id)
|
||||||
row["over_plan"] = row["accumulated"] + Decimal(str(row["current_quantity"] or 0)) > row["planned_quantity"]
|
row["over_plan"] = row["accumulated"] + Decimal(str(row["current_quantity"] or 0)) > row["planned_quantity"]
|
||||||
row["in_selection"] = token is not None and row["item"].system_id == selected_id
|
row["in_selection"] = token is not None and row["item"].system_id == selected_id
|
||||||
|
existing_photos = list(report.photos) if report is not None else []
|
||||||
|
existing_photos.sort(key=lambda p: (p.sort_order, p.id))
|
||||||
return request.app.templates.TemplateResponse("projects/daily_report_form.html", {
|
return request.app.templates.TemplateResponse("projects/daily_report_form.html", {
|
||||||
"request": request, "project": project_obj, "systems": systems,
|
"request": request, "project": project_obj, "systems": systems,
|
||||||
"has_unclassified_items": bool(unclassified), "unclassified_selected": unclassified_selected,
|
"has_unclassified_items": bool(unclassified), "unclassified_selected": unclassified_selected,
|
||||||
"selected_system": selected_system, "rows": rows, "report": report, "errors": errors or [],
|
"selected_system": selected_system, "rows": rows, "report": report, "errors": errors or [],
|
||||||
})
|
"form_values": form_values,
|
||||||
|
"existing_photos": existing_photos,
|
||||||
|
"photo_limit": MAX_PHOTOS_PER_REPORT,
|
||||||
|
"photo_max_bytes": MAX_PHOTO_BYTES,
|
||||||
|
"photo_formats": ", ".join(sorted({ext for ext in ALLOWED_IMAGE_TYPES})),
|
||||||
|
}, status_code=status_code)
|
||||||
|
|
||||||
|
|
||||||
def _parse_system_selection(db, project_id, token):
|
def _parse_system_selection(db, project_id, token):
|
||||||
@@ -146,10 +187,69 @@ async def new_daily_report(request: Request, project_id: int, system_id: str = N
|
|||||||
return _render_form(request, db, _project_or_404(db, project_id), system_id)
|
return _render_form(request, db, _project_or_404(db, project_id), system_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _collect_uploads(files) -> list[tuple[bytes, str | None, str | None]]:
|
||||||
|
"""Read upload payloads into memory (content, original_name, content_type)."""
|
||||||
|
uploads: list[tuple[bytes, str | None, str | None]] = []
|
||||||
|
for upload in files or []:
|
||||||
|
filename = getattr(upload, "filename", "") or ""
|
||||||
|
if not filename.strip():
|
||||||
|
continue
|
||||||
|
content = upload.file.read()
|
||||||
|
uploads.append((content, filename, getattr(upload, "content_type", None)))
|
||||||
|
return uploads
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_uploads(uploads) -> list[str]:
|
||||||
|
"""Pure validation of upload payloads. No filesystem, no DB writes."""
|
||||||
|
from app.services.daily_report_photo_service import validate_upload
|
||||||
|
|
||||||
|
errors: list[str] = []
|
||||||
|
for content, name, ctype in uploads:
|
||||||
|
try:
|
||||||
|
validate_upload(content, name, ctype)
|
||||||
|
except PhotoValidationError as exc:
|
||||||
|
errors.append(f"{name or 'файл'}: {exc}")
|
||||||
|
return errors
|
||||||
|
|
||||||
|
|
||||||
|
def _delete_photo_ids_from_form(form) -> list[int]:
|
||||||
|
ids: list[int] = []
|
||||||
|
for key, value in form.multi_items():
|
||||||
|
if not key.startswith("delete_photo_"):
|
||||||
|
continue
|
||||||
|
if value not in ("1", "on", "true"):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
ids.append(int(key.removeprefix("delete_photo_")))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def _save_report_photos(db, project_obj, report, uploads):
|
||||||
|
"""Persist pre-validated photos; return error list (empty on success)."""
|
||||||
|
if not uploads:
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
persist_photos(
|
||||||
|
db,
|
||||||
|
project_id=project_obj.id,
|
||||||
|
daily_report_id=report.id,
|
||||||
|
uploads=uploads,
|
||||||
|
)
|
||||||
|
except PhotoValidationError as exc:
|
||||||
|
return [str(exc)]
|
||||||
|
except DailyReportPhotoError as exc:
|
||||||
|
return [f"Не удалось сохранить фото: {exc}"]
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{project_id}/daily-reports")
|
@router.post("/{project_id}/daily-reports")
|
||||||
async def create_daily_report(request: Request, project_id: int,
|
async def create_daily_report(request: Request, project_id: int,
|
||||||
report_date: str = Form(...), system_id: str = Form(...),
|
report_date: str = Form(...), system_id: str = Form(...),
|
||||||
notes: str = Form(""), db: Session = Depends(get_db)):
|
notes: str = Form(""),
|
||||||
|
files: list[UploadFile] = File(default=[]),
|
||||||
|
db: Session = Depends(get_db)):
|
||||||
project_obj = _project_or_404(db, project_id)
|
project_obj = _project_or_404(db, project_id)
|
||||||
try:
|
try:
|
||||||
parsed_date = date.fromisoformat(report_date)
|
parsed_date = date.fromisoformat(report_date)
|
||||||
@@ -157,17 +257,32 @@ async def create_daily_report(request: Request, project_id: int,
|
|||||||
raise HTTPException(status_code=400, detail="Invalid report date") from exc
|
raise HTTPException(status_code=400, detail="Invalid report date") from exc
|
||||||
system_id = _parse_system_selection(db, project_id, system_id)
|
system_id = _parse_system_selection(db, project_id, system_id)
|
||||||
form = await request.form()
|
form = await request.form()
|
||||||
|
form_values = {k: v for k, v in form.multi_items() if k != "files"}
|
||||||
quantities, errors = _quantities_from_form(form)
|
quantities, errors = _quantities_from_form(form)
|
||||||
if errors:
|
uploads = _collect_uploads(files)
|
||||||
|
errors.extend(_validate_uploads(uploads))
|
||||||
selection = "unclassified" if system_id is None else system_id
|
selection = "unclassified" if system_id is None else system_id
|
||||||
return _render_form(request, db, project_obj, selection, errors=errors)
|
# Nothing is written yet: the user keeps every already-entered field.
|
||||||
|
if errors:
|
||||||
|
return _render_form(request, db, project_obj, selection, errors=errors,
|
||||||
|
form_values=form_values, status_code=400)
|
||||||
_validate_work_items(db, project_id, system_id, quantities)
|
_validate_work_items(db, project_id, system_id, quantities)
|
||||||
report = DailyReport(project_id=project_id, system_id=system_id, report_date=parsed_date,
|
report = DailyReport(project_id=project_id, system_id=system_id, report_date=parsed_date,
|
||||||
notes=notes.strip() or None)
|
notes=notes.strip() or None)
|
||||||
for item_id, quantity in quantities.items():
|
for item_id, quantity in quantities.items():
|
||||||
report.items.append(DailyReportItem(work_item_id=item_id, completed_quantity=quantity))
|
report.items.append(DailyReportItem(work_item_id=item_id, completed_quantity=quantity))
|
||||||
db.add(report)
|
db.add(report)
|
||||||
|
db.flush()
|
||||||
|
photo_errors = _save_report_photos(db, project_obj, report, uploads)
|
||||||
|
if photo_errors:
|
||||||
|
db.rollback()
|
||||||
|
return _render_form(request, db, project_obj, selection, errors=photo_errors,
|
||||||
|
form_values=form_values, status_code=400)
|
||||||
|
try:
|
||||||
db.commit()
|
db.commit()
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise HTTPException(status_code=500, detail=f"Не удалось создать отчёт: {exc}") from exc
|
||||||
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
@@ -199,10 +314,12 @@ async def view_daily_report(request: Request, project_id: int, report_id: int,
|
|||||||
row["available_quantity"] = info.available_quantity if info else row["current_quantity"]
|
row["available_quantity"] = info.available_quantity if info else row["current_quantity"]
|
||||||
can_del, del_reason = can_delete_report(db, report)
|
can_del, del_reason = can_delete_report(db, report)
|
||||||
system_names = sorted({row["item"].system.name for row in displayed if row["item"].system})
|
system_names = sorted({row["item"].system.name for row in displayed if row["item"].system})
|
||||||
|
photos = sorted(report.photos, key=lambda p: (p.sort_order, p.id))
|
||||||
return request.app.templates.TemplateResponse("projects/daily_report_view.html", {
|
return request.app.templates.TemplateResponse("projects/daily_report_view.html", {
|
||||||
"request": request, "project": project_obj, "report": report,
|
"request": request, "project": project_obj, "report": report,
|
||||||
"rows": displayed, "warnings": warnings, "system_names": system_names,
|
"rows": displayed, "warnings": warnings, "system_names": system_names,
|
||||||
"can_delete_report": can_del, "delete_blocked_reason": del_reason,
|
"can_delete_report": can_del, "delete_blocked_reason": del_reason,
|
||||||
|
"photos": photos,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@@ -219,7 +336,9 @@ async def edit_daily_report(request: Request, project_id: int, report_id: int,
|
|||||||
@router.post("/{project_id}/daily-reports/{report_id}/edit")
|
@router.post("/{project_id}/daily-reports/{report_id}/edit")
|
||||||
async def update_daily_report(request: Request, project_id: int, report_id: int,
|
async def update_daily_report(request: Request, project_id: int, report_id: int,
|
||||||
report_date: str = Form(...), system_id: str = Form(...),
|
report_date: str = Form(...), system_id: str = Form(...),
|
||||||
notes: str = Form(""), db: Session = Depends(get_db)):
|
notes: str = Form(""),
|
||||||
|
files: list[UploadFile] = File(default=[]),
|
||||||
|
db: Session = Depends(get_db)):
|
||||||
project_obj = _project_or_404(db, project_id)
|
project_obj = _project_or_404(db, project_id)
|
||||||
report = _report_or_404(db, project_id, report_id)
|
report = _report_or_404(db, project_id, report_id)
|
||||||
try:
|
try:
|
||||||
@@ -228,10 +347,16 @@ async def update_daily_report(request: Request, project_id: int, report_id: int,
|
|||||||
raise HTTPException(status_code=400, detail="Invalid report date") from exc
|
raise HTTPException(status_code=400, detail="Invalid report date") from exc
|
||||||
system_id = _parse_system_selection(db, project_id, system_id)
|
system_id = _parse_system_selection(db, project_id, system_id)
|
||||||
form = await request.form()
|
form = await request.form()
|
||||||
|
form_values = {k: v for k, v in form.multi_items() if k != "files"}
|
||||||
quantities, errors = _quantities_from_form(form)
|
quantities, errors = _quantities_from_form(form)
|
||||||
if errors:
|
uploads = _collect_uploads(files)
|
||||||
|
errors.extend(_validate_uploads(uploads))
|
||||||
|
delete_ids = _delete_photo_ids_from_form(form)
|
||||||
selection = "unclassified" if system_id is None else system_id
|
selection = "unclassified" if system_id is None else system_id
|
||||||
return _render_form(request, db, project_obj, selection, report, errors)
|
# Nothing is written yet: the user keeps every already-entered field.
|
||||||
|
if errors:
|
||||||
|
return _render_form(request, db, project_obj, selection, report, errors,
|
||||||
|
form_values=form_values, status_code=400)
|
||||||
_validate_work_items(db, project_id, system_id, quantities)
|
_validate_work_items(db, project_id, system_id, quantities)
|
||||||
try:
|
try:
|
||||||
apply_quantities(
|
apply_quantities(
|
||||||
@@ -239,8 +364,31 @@ async def update_daily_report(request: Request, project_id: int, report_id: int,
|
|||||||
new_date=parsed_date, system_id=system_id, notes=notes.strip() or None,
|
new_date=parsed_date, system_id=system_id, notes=notes.strip() or None,
|
||||||
)
|
)
|
||||||
except DailyReportError as exc:
|
except DailyReportError as exc:
|
||||||
selection = "unclassified" if system_id is None else system_id
|
return _render_form(request, db, project_obj, selection, report, [str(exc)],
|
||||||
return _render_form(request, db, project_obj, selection, report, [str(exc)])
|
form_values=form_values, status_code=400)
|
||||||
|
# Photo changes are explicit and separate from the volume lifecycle.
|
||||||
|
try:
|
||||||
|
if delete_ids:
|
||||||
|
owned = {p.id: p for p in report.photos}
|
||||||
|
for photo_id in delete_ids:
|
||||||
|
photo = owned.get(photo_id)
|
||||||
|
if photo is not None:
|
||||||
|
delete_photo(db, photo)
|
||||||
|
if uploads:
|
||||||
|
photo_errors = _save_report_photos(db, project_obj, report, uploads)
|
||||||
|
if photo_errors:
|
||||||
|
db.rollback()
|
||||||
|
return _render_form(request, db, project_obj, selection, report,
|
||||||
|
photo_errors, form_values=form_values, status_code=400)
|
||||||
|
db.commit()
|
||||||
|
except DailyReportPhotoError as exc:
|
||||||
|
db.rollback()
|
||||||
|
return _render_form(request, db, project_obj, selection, report,
|
||||||
|
[f"Не удалось обновить фотографии: {exc}"], form_values=form_values, status_code=400)
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
return _render_form(request, db, project_obj, selection, report,
|
||||||
|
[f"Не удалось сохранить фотографии: {exc}"], form_values=form_values, status_code=400)
|
||||||
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
@@ -288,13 +436,63 @@ def _ks2_closed_item_ids(db, report_id):
|
|||||||
async def delete_daily_report(project_id: int, report_id: int, db: Session = Depends(get_db)):
|
async def delete_daily_report(project_id: int, report_id: int, db: Session = Depends(get_db)):
|
||||||
_project_or_404(db, project_id)
|
_project_or_404(db, project_id)
|
||||||
report = _report_or_404(db, project_id, report_id)
|
report = _report_or_404(db, project_id, report_id)
|
||||||
|
# Photo files live outside SQLite — collect keys before the cascade drops rows.
|
||||||
|
photo_keys = [p.storage_key for p in report.photos]
|
||||||
try:
|
try:
|
||||||
delete_report(db, report)
|
delete_report(db, report)
|
||||||
except DailyReportError as exc:
|
except DailyReportError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
from app.services.daily_report_photo_service import remove_photo_file
|
||||||
|
for key in photo_keys:
|
||||||
|
remove_photo_file(key)
|
||||||
return RedirectResponse(f"/projects/{project_id}/daily-reports", status_code=303)
|
return RedirectResponse(f"/projects/{project_id}/daily-reports", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/daily-reports/{report_id}/photos/{photo_id}/delete")
|
||||||
|
async def delete_daily_report_photo(
|
||||||
|
project_id: int, report_id: int, photo_id: int, db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""Explicit photo removal. Never implied by editing volumes or systems."""
|
||||||
|
_project_or_404(db, project_id)
|
||||||
|
report = _report_or_404(db, project_id, report_id)
|
||||||
|
photo = next((p for p in report.photos if p.id == photo_id), None)
|
||||||
|
if photo is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Photo not found")
|
||||||
|
try:
|
||||||
|
delete_photo(db, photo)
|
||||||
|
db.commit()
|
||||||
|
except DailyReportPhotoError as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
except Exception as exc:
|
||||||
|
db.rollback()
|
||||||
|
raise HTTPException(status_code=500, detail=f"Не удалось удалить фото: {exc}") from exc
|
||||||
|
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/daily-reports/{report_id}/photos/{photo_id}")
|
||||||
|
async def view_daily_report_photo(
|
||||||
|
project_id: int, report_id: int, photo_id: int, db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""Serve the stored photo bytes. Read-only; no regeneration."""
|
||||||
|
_project_or_404(db, project_id)
|
||||||
|
report = _report_or_404(db, project_id, report_id)
|
||||||
|
photo = next((p for p in report.photos if p.id == photo_id), None)
|
||||||
|
if photo is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Photo not found")
|
||||||
|
try:
|
||||||
|
content = photo_file_bytes(photo)
|
||||||
|
except PhotoNotFoundError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||||
|
filename = photo.original_name or f"photo_{photo.id}"
|
||||||
|
from app.exporters import content_disposition
|
||||||
|
return Response(
|
||||||
|
content=content,
|
||||||
|
media_type=photo.content_type,
|
||||||
|
headers={"Content-Disposition": content_disposition(filename)},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{project_id}/daily-reports/{report_id}/items/{item_id}/delete")
|
@router.post("/{project_id}/daily-reports/{report_id}/items/{item_id}/delete")
|
||||||
async def delete_daily_report_item(
|
async def delete_daily_report_item(
|
||||||
project_id: int, report_id: int, item_id: int, db: Session = Depends(get_db)
|
project_id: int, report_id: int, item_id: int, db: Session = Depends(get_db)
|
||||||
|
|||||||
@@ -0,0 +1,329 @@
|
|||||||
|
"""Daily Report photo service: validate, persist, resolve, delete.
|
||||||
|
|
||||||
|
Photos are attached to the whole Daily Report (REQ). Files live under the
|
||||||
|
managed document storage root; only metadata is stored in SQLite.
|
||||||
|
|
||||||
|
Storage key layout (server-generated only, never derived from user input):
|
||||||
|
|
||||||
|
projects/{project_id}/daily_reports/{daily_report_id}/photos/{uuid}.{ext}
|
||||||
|
|
||||||
|
Transaction ownership: the service does NOT commit. The caller manages the
|
||||||
|
database transaction. Filesystem writes use compensating cleanup on failure.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import tempfile
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.config import document_storage_root
|
||||||
|
from app.models.daily_report_photo import DailyReportPhoto
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Limits and supported formats
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Accepted raster formats. Extension is only a hint — content is validated
|
||||||
|
# against magic bytes so a renamed non-image cannot be stored as a photo.
|
||||||
|
ALLOWED_IMAGE_TYPES: dict[str, str] = {
|
||||||
|
".jpg": "image/jpeg",
|
||||||
|
".jpeg": "image/jpeg",
|
||||||
|
".png": "image/png",
|
||||||
|
".webp": "image/webp",
|
||||||
|
}
|
||||||
|
ALLOWED_CONTENT_TYPES = frozenset(ALLOWED_IMAGE_TYPES.values())
|
||||||
|
|
||||||
|
# Hard limit per file. Larger uploads are rejected with a clear message.
|
||||||
|
MAX_PHOTO_BYTES = 10 * 1024 * 1024 # 10 MB
|
||||||
|
# Hard limit per Daily Report so a report cannot be flooded with uploads.
|
||||||
|
MAX_PHOTOS_PER_REPORT = 20
|
||||||
|
|
||||||
|
_SAFE_SEGMENT = re.compile(r"^[A-Za-z0-9._-]+$")
|
||||||
|
|
||||||
|
|
||||||
|
class DailyReportPhotoError(ValueError):
|
||||||
|
"""Domain error raised by the photo service."""
|
||||||
|
|
||||||
|
|
||||||
|
class PhotoNotFoundError(DailyReportPhotoError):
|
||||||
|
"""Photo row or physical file is missing."""
|
||||||
|
|
||||||
|
|
||||||
|
class PhotoPathError(DailyReportPhotoError):
|
||||||
|
"""storage_key is unsafe or escapes the storage root."""
|
||||||
|
|
||||||
|
|
||||||
|
class PhotoValidationError(DailyReportPhotoError):
|
||||||
|
"""Uploaded file is not an accepted image or exceeds the limits."""
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Content validation
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def compute_content_hash(content: bytes) -> str:
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
return hashlib.sha256(content).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _sniff_extension(content: bytes) -> str | None:
|
||||||
|
"""Return the image extension implied by magic bytes, or None."""
|
||||||
|
if content.startswith(b"\xff\xd8\xff"):
|
||||||
|
return ".jpg"
|
||||||
|
if content.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||||
|
return ".png"
|
||||||
|
if len(content) >= 12 and content[:4] == b"RIFF" and content[8:12] == b"WEBP":
|
||||||
|
return ".webp"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _extension_for_name(filename: str | None) -> str:
|
||||||
|
if not filename:
|
||||||
|
return ""
|
||||||
|
return Path(str(filename)).suffix.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def validate_upload(content: bytes, original_name: str | None, content_type: str | None) -> tuple[str, str]:
|
||||||
|
"""Validate an uploaded photo. Returns (extension, content_type).
|
||||||
|
|
||||||
|
The original file name is never used as a path — only its extension is
|
||||||
|
consulted as a hint and then cross-checked against the magic bytes.
|
||||||
|
"""
|
||||||
|
if not isinstance(content, (bytes, bytearray)):
|
||||||
|
raise PhotoValidationError("Файл фотографии повреждён")
|
||||||
|
content = bytes(content)
|
||||||
|
if not content:
|
||||||
|
raise PhotoValidationError("Файл фотографии пуст")
|
||||||
|
if len(content) > MAX_PHOTO_BYTES:
|
||||||
|
limit_mb = MAX_PHOTO_BYTES // (1024 * 1024)
|
||||||
|
raise PhotoValidationError(
|
||||||
|
f"Файл слишком большой: {len(content) / (1024 * 1024):.1f} МБ "
|
||||||
|
f"при лимите {limit_mb} МБ"
|
||||||
|
)
|
||||||
|
|
||||||
|
sniffed = _sniff_extension(content)
|
||||||
|
if sniffed is None:
|
||||||
|
raise PhotoValidationError(
|
||||||
|
"Неподдерживаемый формат файла: допускаются JPEG, PNG и WebP"
|
||||||
|
)
|
||||||
|
|
||||||
|
name_ext = _extension_for_name(original_name)
|
||||||
|
# Declared extension is only a hint; the content decides the real type.
|
||||||
|
if name_ext and name_ext in ALLOWED_IMAGE_TYPES and name_ext != sniffed and not (
|
||||||
|
sniffed == ".jpg" and name_ext == ".jpeg"
|
||||||
|
):
|
||||||
|
raise PhotoValidationError(
|
||||||
|
f"Содержимое файла не соответствует расширению {name_ext}: "
|
||||||
|
f"ожидается {ALLOWED_IMAGE_TYPES[sniffed]}"
|
||||||
|
)
|
||||||
|
|
||||||
|
declared_type = (content_type or "").split(";")[0].strip().lower()
|
||||||
|
real_type = ALLOWED_IMAGE_TYPES[sniffed]
|
||||||
|
if declared_type and declared_type in ALLOWED_CONTENT_TYPES and declared_type != real_type:
|
||||||
|
raise PhotoValidationError(
|
||||||
|
f"Тип содержимого не соответствует формату файла: {declared_type} ≠ {real_type}"
|
||||||
|
)
|
||||||
|
return sniffed, real_type
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Storage paths
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def build_photo_storage_key(
|
||||||
|
project_id: int,
|
||||||
|
daily_report_id: int,
|
||||||
|
extension: str,
|
||||||
|
token: str | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Server-generated relative storage key. Never uses the original file name."""
|
||||||
|
project_id = int(project_id)
|
||||||
|
daily_report_id = int(daily_report_id)
|
||||||
|
if project_id <= 0 or daily_report_id <= 0:
|
||||||
|
raise PhotoPathError("project_id and daily_report_id must be positive")
|
||||||
|
ext = extension.lstrip(".").lower()
|
||||||
|
if not _SAFE_SEGMENT.match(ext):
|
||||||
|
raise PhotoPathError(f"Invalid extension: {extension!r}")
|
||||||
|
if f".{ext}" not in ALLOWED_IMAGE_TYPES:
|
||||||
|
raise PhotoPathError(f"Unsupported extension: {extension!r}")
|
||||||
|
name = f"{token or uuid.uuid4().hex}.{ext}"
|
||||||
|
return (
|
||||||
|
f"projects/{project_id}/daily_reports/{daily_report_id}/photos/{name}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_photo_path(storage_key: str) -> Path:
|
||||||
|
"""Map a relative storage key to an absolute path inside the storage root."""
|
||||||
|
if not storage_key or not str(storage_key).strip():
|
||||||
|
raise PhotoPathError("storage_key is required")
|
||||||
|
key = str(storage_key).replace("\\", "/").strip()
|
||||||
|
if key.startswith("/") or re.match(r"^[A-Za-z]:", key):
|
||||||
|
raise PhotoPathError("storage_key must be relative")
|
||||||
|
if ".." in Path(key).parts:
|
||||||
|
raise PhotoPathError("storage_key must not contain '..'")
|
||||||
|
root = document_storage_root().resolve()
|
||||||
|
candidate = (root / key).resolve()
|
||||||
|
try:
|
||||||
|
candidate.relative_to(root)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise PhotoPathError("storage_key escapes storage root") from exc
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Persist / delete
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def count_photos(db: Session, daily_report_id: int) -> int:
|
||||||
|
return int(
|
||||||
|
db.execute(
|
||||||
|
select(func.count()).select_from(DailyReportPhoto).where(
|
||||||
|
DailyReportPhoto.daily_report_id == int(daily_report_id)
|
||||||
|
)
|
||||||
|
).scalar()
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def persist_photo(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
project_id: int,
|
||||||
|
daily_report_id: int,
|
||||||
|
content: bytes,
|
||||||
|
original_name: str | None = None,
|
||||||
|
content_type: str | None = None,
|
||||||
|
sort_order: int = 0,
|
||||||
|
) -> DailyReportPhoto:
|
||||||
|
"""Validate, store photo bytes on disk and stage a DailyReportPhoto row.
|
||||||
|
|
||||||
|
Does NOT commit. The caller owns the transaction. On failure the file
|
||||||
|
created by this call is removed (compensating cleanup); existing photos
|
||||||
|
are never touched.
|
||||||
|
"""
|
||||||
|
content = bytes(content)
|
||||||
|
extension, real_type = validate_upload(content, original_name, content_type)
|
||||||
|
|
||||||
|
existing = count_photos(db, daily_report_id)
|
||||||
|
if existing >= MAX_PHOTOS_PER_REPORT:
|
||||||
|
raise PhotoValidationError(
|
||||||
|
f"К отчёту уже прикреплено максимальное количество фото "
|
||||||
|
f"({MAX_PHOTOS_PER_REPORT})"
|
||||||
|
)
|
||||||
|
|
||||||
|
storage_key = build_photo_storage_key(project_id, daily_report_id, extension)
|
||||||
|
path = resolve_photo_path(storage_key)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
tmp_fd, tmp_name = tempfile.mkstemp(
|
||||||
|
dir=str(path.parent), prefix=".tmp-photo-", suffix=extension
|
||||||
|
)
|
||||||
|
tmp_path = Path(tmp_name)
|
||||||
|
try:
|
||||||
|
with os.fdopen(tmp_fd, "wb") as handle:
|
||||||
|
handle.write(content)
|
||||||
|
handle.flush()
|
||||||
|
os.fsync(handle.fileno())
|
||||||
|
os.replace(tmp_path, path)
|
||||||
|
except Exception:
|
||||||
|
if tmp_path.exists():
|
||||||
|
try:
|
||||||
|
tmp_path.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
photo = DailyReportPhoto(
|
||||||
|
project_id=int(project_id),
|
||||||
|
daily_report_id=int(daily_report_id),
|
||||||
|
storage_key=storage_key,
|
||||||
|
# Display only. Never used to build a path.
|
||||||
|
original_name=(str(original_name).strip()[:255] or None) if original_name else None,
|
||||||
|
content_type=real_type,
|
||||||
|
file_size=len(content),
|
||||||
|
content_hash=compute_content_hash(content),
|
||||||
|
sort_order=int(sort_order),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
db.add(photo)
|
||||||
|
db.flush()
|
||||||
|
except Exception:
|
||||||
|
# Compensating cleanup: the file must not outlive a failed row insert.
|
||||||
|
remove_photo_file(storage_key)
|
||||||
|
raise
|
||||||
|
return photo
|
||||||
|
|
||||||
|
|
||||||
|
def persist_photos(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
project_id: int,
|
||||||
|
daily_report_id: int,
|
||||||
|
uploads: list[tuple[bytes, str | None, str | None]],
|
||||||
|
) -> list[DailyReportPhoto]:
|
||||||
|
"""Persist a batch of uploads. Rolls back all files of the batch on failure.
|
||||||
|
|
||||||
|
`uploads` is a list of (content, original_name, content_type).
|
||||||
|
"""
|
||||||
|
created: list[DailyReportPhoto] = []
|
||||||
|
keys: list[str] = []
|
||||||
|
try:
|
||||||
|
for index, (content, name, ctype) in enumerate(uploads):
|
||||||
|
photo = persist_photo(
|
||||||
|
db,
|
||||||
|
project_id=project_id,
|
||||||
|
daily_report_id=daily_report_id,
|
||||||
|
content=content,
|
||||||
|
original_name=name,
|
||||||
|
content_type=ctype,
|
||||||
|
sort_order=index,
|
||||||
|
)
|
||||||
|
created.append(photo)
|
||||||
|
keys.append(photo.storage_key)
|
||||||
|
except Exception:
|
||||||
|
for key in keys:
|
||||||
|
remove_photo_file(key)
|
||||||
|
raise
|
||||||
|
return created
|
||||||
|
|
||||||
|
|
||||||
|
def remove_photo_file(storage_key: str) -> None:
|
||||||
|
"""Best-effort delete of a photo file. Never raises."""
|
||||||
|
try:
|
||||||
|
path = resolve_photo_path(storage_key)
|
||||||
|
except PhotoPathError:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
if path.is_file():
|
||||||
|
path.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def delete_photo(db: Session, photo: DailyReportPhoto) -> None:
|
||||||
|
"""Delete the photo row and its physical file.
|
||||||
|
|
||||||
|
Row removal is the caller's transaction; the file is removed after the
|
||||||
|
row is gone so a rollback keeps the file reachable.
|
||||||
|
"""
|
||||||
|
storage_key = photo.storage_key
|
||||||
|
db.delete(photo)
|
||||||
|
db.flush()
|
||||||
|
remove_photo_file(storage_key)
|
||||||
|
|
||||||
|
|
||||||
|
def photo_file_bytes(photo: DailyReportPhoto) -> bytes:
|
||||||
|
"""Read the photo file. Raises PhotoNotFoundError when missing."""
|
||||||
|
try:
|
||||||
|
path = resolve_photo_path(photo.storage_key)
|
||||||
|
except PhotoPathError as exc:
|
||||||
|
raise PhotoNotFoundError(f"Файл фотографии недоступен: {exc}") from exc
|
||||||
|
if not path.is_file():
|
||||||
|
raise PhotoNotFoundError("Файл фотографии не найден в хранилище")
|
||||||
|
return path.read_bytes()
|
||||||
@@ -13,6 +13,7 @@ from app.config import document_storage_root
|
|||||||
from app.models.agreement import Agreement, AgreementItem
|
from app.models.agreement import Agreement, AgreementItem
|
||||||
from app.models.boq import BoqDocument, Section, System, WorkItem
|
from app.models.boq import BoqDocument, Section, System, WorkItem
|
||||||
from app.models.daily_report import DailyReport, DailyReportItem
|
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.ks2 import KS2, KS2Item, KS2ItemSource
|
||||||
from app.models.ks3 import KS3, KS3KS2
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
from app.models.payment import Payment, PaymentAllocation
|
from app.models.payment import Payment, PaymentAllocation
|
||||||
@@ -38,6 +39,7 @@ DELETE_ORDER = (
|
|||||||
("ks2_item_sources", KS2ItemSource),
|
("ks2_item_sources", KS2ItemSource),
|
||||||
("ks2_items", KS2Item),
|
("ks2_items", KS2Item),
|
||||||
("ks2_documents", KS2),
|
("ks2_documents", KS2),
|
||||||
|
("daily_report_photos", DailyReportPhoto),
|
||||||
("daily_report_items", DailyReportItem),
|
("daily_report_items", DailyReportItem),
|
||||||
("daily_reports", DailyReport),
|
("daily_reports", DailyReport),
|
||||||
("agreement_items", AgreementItem),
|
("agreement_items", AgreementItem),
|
||||||
|
|||||||
@@ -18,12 +18,13 @@
|
|||||||
<h1>{{ 'Редактировать Daily Report' if report else 'Новый Daily Report' }}</h1>
|
<h1>{{ 'Редактировать Daily Report' if report else 'Новый Daily Report' }}</h1>
|
||||||
{% for error in errors %}<div class="alert alert-danger">{{ error }}</div>{% endfor %}
|
{% for error in errors %}<div class="alert alert-danger">{{ error }}</div>{% endfor %}
|
||||||
|
|
||||||
<form method="post" action="{% if report %}/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit{% else %}/projects/{{ project.id }}/daily-reports{% endif %}">
|
<form method="post" enctype="multipart/form-data"
|
||||||
|
action="{% if report %}/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit{% else %}/projects/{{ project.id }}/daily-reports{% endif %}">
|
||||||
<input type="hidden" name="system_id" id="hidden-system-id" value="{{ selected_system.id if selected_system else ('unclassified' if unclassified_selected else '') }}">
|
<input type="hidden" name="system_id" id="hidden-system-id" value="{{ selected_system.id if selected_system else ('unclassified' if unclassified_selected else '') }}">
|
||||||
<div class="card card-body mb-3">
|
<div class="card card-body mb-3">
|
||||||
<div class="row g-3">
|
<div class="row g-3">
|
||||||
<div class="col-md-4"><label for="report-date" class="form-label">Дата отчёта</label><input id="report-date" class="form-control" type="date" name="report_date" required value="{{ report.report_date.isoformat() if report else '' }}"></div>
|
<div class="col-md-4"><label for="report-date" class="form-label">Дата отчёта</label><input id="report-date" class="form-control" type="date" name="report_date" required value="{{ form_values.get('report_date', report.report_date.isoformat() if report else '') }}"></div>
|
||||||
<div class="col-md-8"><label for="notes" class="form-label">Комментарий</label><input id="notes" class="form-control" name="notes" value="{{ report.notes if report and report.notes else '' }}"></div>
|
<div class="col-md-8"><label for="notes" class="form-label">Комментарий</label><input id="notes" class="form-control" name="notes" value="{{ form_values.get('notes', report.notes if report and report.notes else '') }}"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -88,6 +89,50 @@
|
|||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<div id="selected-empty" class="card-footer text-muted" hidden>Пока ничего не добавлено.</div>
|
<div id="selected-empty" class="card-footer text-muted" hidden>Пока ничего не добавлено.</div>
|
||||||
|
|
||||||
|
<!-- ============ Фотоотчёт ============ -->
|
||||||
|
<div class="card-footer border-top" id="photo-zone">
|
||||||
|
<div class="d-flex justify-content-between align-items-center mb-2">
|
||||||
|
<strong>Фотоотчёт</strong>
|
||||||
|
<span class="text-muted small">до {{ photo_limit }} фото · до {{ (photo_max_bytes / 1024 / 1024)|round(0)|int }} МБ · {{ photo_formats }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="form-text mb-2">Фото привязываются к отчёту целиком. Можно выбрать файлы на компьютере или телефоне — из галереи или камерой, если это поддерживает устройство.</div>
|
||||||
|
|
||||||
|
{% if existing_photos %}
|
||||||
|
<div class="mb-3">
|
||||||
|
<div class="form-label">Сохранённые фотографии</div>
|
||||||
|
<div class="row g-2" id="existing-photos">
|
||||||
|
{% for photo in existing_photos %}
|
||||||
|
<div class="col-4 col-md-2">
|
||||||
|
<div class="border rounded p-1">
|
||||||
|
<img class="img-fluid rounded w-100"
|
||||||
|
style="aspect-ratio: 4 / 3; object-fit: cover;"
|
||||||
|
src="/projects/{{ project.id }}/daily-reports/{{ report.id }}/photos/{{ photo.id }}"
|
||||||
|
alt="{{ photo.original_name or ('Фото ' ~ photo.id) }}">
|
||||||
|
<div class="form-check mt-1">
|
||||||
|
<input class="form-check-input" type="checkbox"
|
||||||
|
name="delete_photo_{{ photo.id }}" value="1"
|
||||||
|
id="delete_photo_{{ photo.id }}">
|
||||||
|
<label class="form-check-label small text-danger"
|
||||||
|
for="delete_photo_{{ photo.id }}">Удалить</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<div class="form-text">Существующие фото удаляются только по явной отметке «Удалить» и сохранению формы.</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="mb-2">
|
||||||
|
<label for="photo-input" class="form-label">Добавить фотографии</label>
|
||||||
|
<input class="form-control" type="file" id="photo-input" name="files"
|
||||||
|
accept="image/jpeg,image/png,image/webp,image/*" multiple>
|
||||||
|
</div>
|
||||||
|
<div class="row g-2" id="photo-preview"></div>
|
||||||
|
<div id="photo-empty" class="form-text">Новые файлы будут показаны миниатюрами здесь.</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="card-footer d-flex justify-content-between">
|
<div class="card-footer d-flex justify-content-between">
|
||||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/daily-reports">Отмена</a>
|
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/daily-reports">Отмена</a>
|
||||||
<button class="btn btn-primary" type="submit">{{ 'Сохранить изменения' if report else 'Создать отчёт' }}</button>
|
<button class="btn btn-primary" type="submit">{{ 'Сохранить изменения' if report else 'Создать отчёт' }}</button>
|
||||||
@@ -213,6 +258,51 @@
|
|||||||
|
|
||||||
rebuildSelected();
|
rebuildSelected();
|
||||||
applyPickerFilter();
|
applyPickerFilter();
|
||||||
|
|
||||||
|
// ---------- Фотоотчёт: миниатюры до сохранения ----------
|
||||||
|
const photoInput = document.getElementById('photo-input');
|
||||||
|
const photoPreview = document.getElementById('photo-preview');
|
||||||
|
const photoEmpty = document.getElementById('photo-empty');
|
||||||
|
if (photoInput && photoPreview) {
|
||||||
|
const renderPhotoPreview = () => {
|
||||||
|
photoPreview.textContent = '';
|
||||||
|
const files = [...photoInput.files];
|
||||||
|
if (photoEmpty) photoEmpty.hidden = files.length !== 0;
|
||||||
|
files.forEach((file, index) => {
|
||||||
|
const col = document.createElement('div');
|
||||||
|
col.className = 'col-4 col-md-2';
|
||||||
|
const box = document.createElement('div');
|
||||||
|
box.className = 'border rounded p-1';
|
||||||
|
const img = document.createElement('img');
|
||||||
|
img.className = 'img-fluid rounded w-100';
|
||||||
|
img.style.aspectRatio = '4 / 3';
|
||||||
|
img.style.objectFit = 'cover';
|
||||||
|
img.alt = file.name;
|
||||||
|
try {
|
||||||
|
img.src = URL.createObjectURL(file);
|
||||||
|
img.onload = () => URL.revokeObjectURL(img.src);
|
||||||
|
} catch { /* preview is best-effort */ }
|
||||||
|
const name = document.createElement('div');
|
||||||
|
name.className = 'small text-muted text-truncate';
|
||||||
|
name.textContent = file.name;
|
||||||
|
name.title = file.name;
|
||||||
|
const remove = document.createElement('button');
|
||||||
|
remove.type = 'button';
|
||||||
|
remove.className = 'btn btn-sm btn-outline-danger w-100 mt-1';
|
||||||
|
remove.textContent = 'Убрать';
|
||||||
|
remove.addEventListener('click', () => {
|
||||||
|
const dt = new DataTransfer();
|
||||||
|
[...photoInput.files].forEach((f, i) => { if (i !== index) dt.items.add(f); });
|
||||||
|
photoInput.files = dt.files;
|
||||||
|
renderPhotoPreview();
|
||||||
|
});
|
||||||
|
box.append(img, name, remove);
|
||||||
|
col.appendChild(box);
|
||||||
|
photoPreview.appendChild(col);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
photoInput.addEventListener('change', renderPhotoPreview);
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -46,6 +46,37 @@
|
|||||||
</tr>
|
</tr>
|
||||||
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">В отчёте нет рабочих позиций.</td></tr>{% endfor %}</tbody>
|
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">В отчёте нет рабочих позиций.</td></tr>{% endfor %}</tbody>
|
||||||
</table></div></div>
|
</table></div></div>
|
||||||
|
|
||||||
|
<section class="card mt-4" id="photo-section">
|
||||||
|
<div class="card-header d-flex justify-content-between align-items-center">
|
||||||
|
<strong>Фотоотчёт</strong>
|
||||||
|
<span class="text-muted small">{{ photos|length }} фото</span>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
{% if photos %}
|
||||||
|
<div class="row g-2">
|
||||||
|
{% for photo in photos %}
|
||||||
|
<div class="col-6 col-md-3 col-lg-2">
|
||||||
|
<a href="/projects/{{ project.id }}/daily-reports/{{ report.id }}/photos/{{ photo.id }}"
|
||||||
|
target="_blank" rel="noopener" class="d-block">
|
||||||
|
<img class="img-fluid rounded border w-100"
|
||||||
|
style="aspect-ratio: 4 / 3; object-fit: cover;"
|
||||||
|
src="/projects/{{ project.id }}/daily-reports/{{ report.id }}/photos/{{ photo.id }}"
|
||||||
|
alt="{{ photo.original_name or ('Фото ' ~ photo.id) }}"
|
||||||
|
loading="lazy">
|
||||||
|
</a>
|
||||||
|
<div class="small text-muted text-truncate" title="{{ photo.original_name or '' }}">
|
||||||
|
{{ photo.original_name or ('Фото ' ~ photo.id) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="text-muted">Фотографии не прикреплены. Их можно добавить при редактировании отчёта.</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<div class="mt-3"><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-outline-secondary">К списку отчётов</a></div>
|
<div class="mt-3"><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-outline-secondary">К списку отчётов</a></div>
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
# REQ-daily-report-photo-attachments
|
||||||
|
|
||||||
|
Task: `docs/tasks/REQ-daily-report-photo-attachments.md`
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
DONE
|
||||||
|
|
||||||
|
### What was done
|
||||||
|
|
||||||
|
Фотографии привязываются к Daily Report **целиком** (не к отдельным позициям). Реализованы загрузка, просмотр, редактирование, явное удаление, безопасное локальное хранение и перенос фото при экспорте/импорте проекта. Бизнес-логика КС-2/КС-3/платежей и шаблоны форм не менялись.
|
||||||
|
|
||||||
|
**Модель и миграция**
|
||||||
|
|
||||||
|
- `app/models/daily_report_photo.py` — `DailyReportPhoto`: `project_id`, `daily_report_id` (FK, cascade `delete-orphan` от `DailyReport.photos`), `storage_key`, `original_name` (только подпись), `content_type`, `file_size`, `content_hash`, `sort_order`, `created_at`.
|
||||||
|
- `app/models/daily_report.py` — связь `DailyReport.photos`.
|
||||||
|
- Миграция `20261015_daily_report_photos` в `app/database/migrations.py` (raw-sqlite3 стиль проекта): таблица + 3 индекса.
|
||||||
|
- `app/main.py` — регистрация модели.
|
||||||
|
|
||||||
|
**Сервис `app/services/daily_report_photo_service.py`**
|
||||||
|
|
||||||
|
Архитектура повторяет `document_artifact_service`: `DB-метаданные → storage_key → файлы в DOCUMENT_STORAGE_ROOT`. Формат пути (генерируется только сервером, никогда из имени файла):
|
||||||
|
|
||||||
|
```
|
||||||
|
projects/{project_id}/daily_reports/{daily_report_id}/photos/{uuid}.{ext}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `validate_upload(content, original_name, content_type)` → `(ext, content_type)`: размер, magic bytes (`FF D8 FF` JPEG / `89 50 4E 47` PNG / `RIFF….WEBP`), сверка расширения и content-type с содержимым.
|
||||||
|
- `build_photo_storage_key` / `resolve_photo_path` — защита от traversal (`..`, абсолютные пути, выход из корня), `original_name` не участвует в построении пути.
|
||||||
|
- `persist_photo` / `persist_photos` — без `commit` (транзакцию ведёт вызывающий), tmp+`os.replace`, компенсирующая очистка файла при ошибке.
|
||||||
|
- `delete_photo` — удаляет строку + файл; `remove_photo_file` — best-effort.
|
||||||
|
- `photo_file_bytes` — чтение файла, `PhotoNotFoundError` при отсутствии.
|
||||||
|
|
||||||
|
**Лимиты и форматы (ограничения)**
|
||||||
|
|
||||||
|
| Параметр | Значение |
|
||||||
|
|---|---|
|
||||||
|
| Форматы | JPEG (`.jpg`/`.jpeg`), PNG (`.png`), WebP (`.webp`) |
|
||||||
|
| Размер файла | ≤ **10 МБ** (`MAX_PHOTO_BYTES`) |
|
||||||
|
| Количество на отчёт | ≤ **20** (`MAX_PHOTOS_PER_REPORT`) |
|
||||||
|
| Проверка типа | magic bytes + сверка с расширением и content-type |
|
||||||
|
| Имя файла | только подпись (≤255 символов), в пути не используется |
|
||||||
|
|
||||||
|
**Форма и просмотр**
|
||||||
|
|
||||||
|
- `daily_report_form.html`: форма переведена на `multipart/form-data`; блок «Фотоотчёт» — `<input type="file" accept="image/jpeg,image/png,image/webp,image/*" multiple>` (без `capture`, чтобы на телефоне давался выбор «из галереи или камера»), миниатюры выбранных файлов через `URL.createObjectURL` с кнопкой «Убрать» на каждое, при редактировании — «Сохранённые фотографии» с явным чекбоксом «Удалить». Поле файла не `required` — лёгкий сценарий ввода объёмов не заблокирован.
|
||||||
|
- `daily_report_view.html`: секция «Фотоотчёт» с галереей (клик открывает оригинал).
|
||||||
|
- Роутер `daily_reports.py`: `GET …/photos/{photo_id}` (отдача файла), `POST …/photos/{photo_id}/delete` (явное удаление), `POST …/delete` отчёта убирает файлы фото после каскадного удаления строк.
|
||||||
|
|
||||||
|
**Ошибки и сохранение введённых данных**
|
||||||
|
|
||||||
|
- Валидация всех загрузок выполняется **до записи** (`_validate_uploads`): при ошибке ничего не сохраняется, форма возвращается с `status_code=400`, дата/комментарий/количества восстанавливаются из `form_values` (новый параметр `_render_form`).
|
||||||
|
- Исходный Excel и бизнес-логика КС-2/КС-3/платежей не затронуты; сторнирование финансовых документов не трогает фото (тесты 8-го пункта).
|
||||||
|
|
||||||
|
**Экспорт / импорт проекта**
|
||||||
|
|
||||||
|
По образцу `document_artifacts`:
|
||||||
|
- экспорт: `daily_report_photos.json` (опциональный файл — старые архивы без него импортируются) + бинарные файлы под `photos/{daily_report_export_id}/{photo_id}.bin`, `daily_report_export_id` ссылается на `daily_reports.json`;
|
||||||
|
- импорт: валидация полей/ссылок/`archive_path`/`content_hash`/`file_size`/`content_type`, контрольные суммы ZIP, отсутствие «сирот», восстановление строк и файлов с новым `build_photo_storage_key`, компенсирующая очистка при сбое.
|
||||||
|
|
||||||
|
**Сброс базы**
|
||||||
|
|
||||||
|
`daily_report_photos` добавлен в `DELETE_ORDER` (перед `daily_reports`); физические файлы удаляются существующей очисткой `projects/<pid>/`.
|
||||||
|
|
||||||
|
### Changed files
|
||||||
|
|
||||||
|
| Файл | Изменение |
|
||||||
|
|---|---|
|
||||||
|
| `app/models/daily_report_photo.py` | новый — модель метаданных фото |
|
||||||
|
| `app/services/daily_report_photo_service.py` | новый — валидация, хранение, удаление |
|
||||||
|
| `app/database/migrations.py` | миграция `20261015_daily_report_photos` |
|
||||||
|
| `app/models/daily_report.py` | связь `photos` |
|
||||||
|
| `app/main.py` | регистрация модели |
|
||||||
|
| `app/routers/daily_reports.py` | multipart, загрузка/удаление фото, `form_values`, endpoint-ы фото |
|
||||||
|
| `app/templates/projects/daily_report_form.html` | блок «Фотоотчёт», миниатюры, явное удаление |
|
||||||
|
| `app/templates/projects/daily_report_view.html` | галерея фото |
|
||||||
|
| `app/exporters/project_export.py` | `daily_report_photos.json` + файлы `photos/` |
|
||||||
|
| `app/exporters/project_import.py` | валидация и восстановление фото |
|
||||||
|
| `app/services/database_reset.py` | `daily_report_photos` в `DELETE_ORDER` |
|
||||||
|
| `tests/test_req_daily_report_photos.py` | новый — 21 regression test |
|
||||||
|
|
||||||
|
Не относится к REQ (рабочее дерево, не коммичено): изменения POST-E2E (`excel_importer.py`, `package_service.py`, `boq.py`, `projects.py`, три шаблона, три тест-файла) и BUG-UI (`project_export.py`, частично пересекается с правками REQ).
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
**Добавлено `tests/test_req_daily_report_photos.py` — 21 tests:**
|
||||||
|
|
||||||
|
1. Создание: `test_create_report_with_multiple_photos` (2 фото, метаданные, файлы в storage), `test_create_report_without_photos`.
|
||||||
|
2. Редактирование: `test_edit_add_and_explicitly_delete_photos` (просмотр существующих → добавление → явное удаление одного; файл удалён из storage), `test_photo_delete_endpoint_is_explicit`.
|
||||||
|
3. Некорректные файлы: `test_unsupported_file_rejected_and_form_data_preserved` (`.exe` → 400, дата/заметка/количество сохранены, отчёт не создан), `test_oversized_file_rejected` (>10 МБ), `test_renamed_non_image_rejected`, `test_extension_content_mismatch_rejected`, `test_validate_accepts_jpeg_png_webp`.
|
||||||
|
4. Безопасный путь: `test_storage_key_is_server_generated_and_safe`, `test_storage_key_rejects_traversal_and_bad_extension`, `test_original_name_never_used_as_path` (имя `../../evil/../payload.jpg` не попадает в путь).
|
||||||
|
5. `test_photos_survive_volume_edits_and_system_switch` — фото переживают смену количества/заметки.
|
||||||
|
6. Экспорт/импорт: `test_export_import_roundtrip_preserves_photos` (ZIP `photos/` + `daily_report_photos.json`, импорт, **повторный** экспорт/импорт), `test_export_without_photos_still_valid`.
|
||||||
|
7. `test_database_reset_clears_photos_and_files` — строки и файлы удалены.
|
||||||
|
8. Финансы не трогают фото: `test_ks2_storno_does_not_delete_photos`, `test_ks3_and_payment_storno_do_not_delete_photos`, `test_delete_report_cleans_photo_files`.
|
||||||
|
11. Лёгкий сценарий: `test_photo_input_is_optional_on_the_form`, `test_photo_limit_enforced` (лимит 20).
|
||||||
|
|
||||||
|
**Результаты проверок:**
|
||||||
|
|
||||||
|
- `pytest -q` (полный набор): **721 passed, 7 failed**. Все 7 падений pre-existing (те же были на чистом дереве до изменений и в предыдущей задаче): `test_project_dashboard`, `test_work_journal`, `test_task013_regressions` (3), `test_task014_regressions`, `test_project_workflow_regressions` — копируют реальную БД пользователя и ожидают project id=2. Регрессий нет: существующие тесты Daily Reports, KS-2/KS-3, экспорта/импорта зелёные.
|
||||||
|
- Playwright UI smoke: **18/18** (скриншоты `_req_photo_ui_out/`): блок «Фотоотчёт», `accept`/`multiple`, миниатюры и «Убрать», сохранение и галерея, просмотр существующих при редактировании, явное удаление, ошибка неподдерживаемого файла с сохранением введённых данных, 380px без переполнения.
|
||||||
|
- `git diff --check`: без ошибок пробелов.
|
||||||
|
|
||||||
|
### Deviations
|
||||||
|
|
||||||
|
None.
|
||||||
|
|
||||||
|
### Follow-up / Open Questions
|
||||||
|
|
||||||
|
- `original_name` хранится как подпись; при экспорте/импорте переносится, но не влияет на имя файла в storage (по требованию безопасности).
|
||||||
|
- Размер/количество фото ограничены константами сервиса (`MAX_PHOTO_BYTES`, `MAX_PHOTOS_PER_REPORT`); если понадобятся настройки уровня проекта — отдельная задача.
|
||||||
|
- Генерация миниатюр на сервере и PDF-фотоальбом — вне рамок требования.
|
||||||
|
- 7 pre-existing падающих тестов на реальной БД (`test_project_dashboard`, `test_work_journal`, `test_task013/014_regressions`, `test_project_workflow_regressions`) — отдельная задача по переводу на self-contained fixtures.
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# REQ — Фотоотчёты в Daily Reports
|
||||||
|
|
||||||
|
## Цель
|
||||||
|
Добавить прикрепление фотоотчёта к ежедневному отчёту (Daily Report), чтобы фотографии подтверждали выполненные за смену работы.
|
||||||
|
|
||||||
|
## Зафиксированное решение
|
||||||
|
**Фотографии привязываются к ежедневному отчёту целиком.** В этой доработке не требуется привязка фотографий к отдельным позициям работ.
|
||||||
|
|
||||||
|
## Функциональные требования
|
||||||
|
1. В форме создания и редактирования Daily Report пользователь может прикрепить несколько фотографий к отчёту.
|
||||||
|
2. Предусмотреть выбор файлов с компьютера и мобильного устройства. На поддерживаемых смартфонах выбор должен позволять выбрать фото из галереи или сделать снимок камерой, если браузер и устройство это поддерживают.
|
||||||
|
3. До сохранения показать выбранные изображения миниатюрами и дать возможность убрать отдельное фото из набора.
|
||||||
|
4. После сохранения фотографии остаются связанными с соответствующим Daily Report и доступны для просмотра на странице отчёта.
|
||||||
|
5. Понятно обрабатывать ошибки загрузки и неподдерживаемые файлы. Не терять уже введённые данные отчёта при ошибке загрузки.
|
||||||
|
6. При редактировании показывать ранее сохранённые фотографии и позволять добавлять новые. Удаление существующей фотографии должно быть явным действием пользователя.
|
||||||
|
7. Хранить файлы локально в управляемом хранилище приложения; в БД хранить метаданные и связь с Daily Report. Использовать безопасные имена/пути файлов; не считать исходное имя файла доверенным путём.
|
||||||
|
8. Учесть фотографии в жизненном цикле проекта:
|
||||||
|
- экспорт включает изображения и метаданные;
|
||||||
|
- импорт восстанавливает изображения и связи с Daily Reports;
|
||||||
|
- повторный экспорт/импорт сохраняет фотографии и корректные ссылки;
|
||||||
|
- сброс базы удаляет метаданные и связанные файлы проекта согласно действующим правилам очистки.
|
||||||
|
9. Удаление или сторнирование финансовых документов не должно автоматически удалять фото Daily Report: фотографии относятся к первичному ежедневному отчёту.
|
||||||
|
10. Не включать фотографии автоматически в формы КС-2/КС-3. Они относятся к Daily Report, если отдельным требованием не определено иное.
|
||||||
|
11. Сохранить лёгкий сценарий Daily Report: фото необязательны и не должны мешать быстрому внесению объёмов.
|
||||||
|
|
||||||
|
## Вне рамок
|
||||||
|
- Привязка фото к отдельным позициям работ.
|
||||||
|
- Генерация PDF-фотоальбома или печатного приложения.
|
||||||
|
- Автоматическое распознавание изображений, геолокации или дат съёмки.
|
||||||
|
- Облачная синхронизация и серверное хранилище.
|
||||||
|
|
||||||
|
## Проверки и тесты
|
||||||
|
- создание Daily Report с несколькими фотографиями и без фотографий;
|
||||||
|
- редактирование: просмотр существующих фото, добавление новых, явное удаление выбранных;
|
||||||
|
- некорректный/неподдерживаемый файл и ошибка загрузки;
|
||||||
|
- безопасное формирование storage path;
|
||||||
|
- фотографии не теряются при редактировании объёмов и переключении систем;
|
||||||
|
- экспорт/импорт проекта сохраняет изображения, метаданные и связь с Daily Report;
|
||||||
|
- сброс базы очищает фотофайлы и метаданные проекта;
|
||||||
|
- удаление/сторнирование KS-2, KS-3 или платежа не удаляет фотографии Daily Report;
|
||||||
|
- существующие тесты Daily Reports, KS-2/KS-3 и экспорта/импорта остаются зелёными.
|
||||||
|
|
||||||
|
## Отчёт агента
|
||||||
|
Указать изменённые файлы и миграции, ограничения размера/формата изображений, поведение загрузки с телефона, результаты полного набора тестов и проверку export/import. Не коммитить без отдельной команды.
|
||||||
@@ -0,0 +1,691 @@
|
|||||||
|
"""REQ: Daily Report photo attachments (upload / view / edit / delete / export-import)."""
|
||||||
|
import datetime
|
||||||
|
import io
|
||||||
|
import zipfile
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from sqlalchemy.pool import StaticPool
|
||||||
|
|
||||||
|
from app.database.database import Base
|
||||||
|
from app.main import app
|
||||||
|
from app.models import boq
|
||||||
|
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
|
||||||
|
from app.models.project import Project
|
||||||
|
from app.routers import (
|
||||||
|
projects as project_router,
|
||||||
|
daily_reports as dr_router,
|
||||||
|
ks2 as ks2_router,
|
||||||
|
ks3 as ks3_router,
|
||||||
|
payments as payments_router,
|
||||||
|
)
|
||||||
|
from app.services.daily_report_photo_service import (
|
||||||
|
MAX_PHOTO_BYTES,
|
||||||
|
MAX_PHOTOS_PER_REPORT,
|
||||||
|
PhotoValidationError,
|
||||||
|
build_photo_storage_key,
|
||||||
|
delete_photo,
|
||||||
|
persist_photo,
|
||||||
|
persist_photos,
|
||||||
|
photo_file_bytes,
|
||||||
|
resolve_photo_path,
|
||||||
|
validate_upload,
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- minimal but magic-byte-valid fixtures --------------------------------
|
||||||
|
|
||||||
|
PNG_BYTES = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
|
||||||
|
JPG_BYTES = b"\xff\xd8\xff\xe0" + b"\x00" * 64
|
||||||
|
WEBP_BYTES = b"RIFF" + b"\x20\x00\x00\x00" + b"WEBP" + b"\x00" * 32
|
||||||
|
|
||||||
|
|
||||||
|
def _engine():
|
||||||
|
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||||
|
Base.metadata.create_all(engine)
|
||||||
|
return engine
|
||||||
|
|
||||||
|
|
||||||
|
def _override(*deps):
|
||||||
|
def override_db():
|
||||||
|
db = TestingSession()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
for dep in deps:
|
||||||
|
app.dependency_overrides[dep] = override_db
|
||||||
|
|
||||||
|
|
||||||
|
def _clear():
|
||||||
|
app.dependency_overrides.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def _post(client, url, **kwargs):
|
||||||
|
"""POST without following redirects so 303 can be asserted."""
|
||||||
|
kwargs.setdefault("follow_redirects", False)
|
||||||
|
return client.request("POST", url, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
TestingSession = None
|
||||||
|
|
||||||
|
|
||||||
|
def _seed(tmp_path, monkeypatch=None, with_report=True):
|
||||||
|
"""Project + effective work item + a Daily Report with no photos yet."""
|
||||||
|
global TestingSession
|
||||||
|
storage = tmp_path / "storage"
|
||||||
|
storage.mkdir(exist_ok=True)
|
||||||
|
import os
|
||||||
|
os.environ["DOCUMENT_STORAGE_ROOT"] = str(storage)
|
||||||
|
engine = _engine()
|
||||||
|
TestingSession = sessionmaker(bind=engine, expire_on_commit=False)
|
||||||
|
with TestingSession() as db:
|
||||||
|
project = Project(name="Фотоотчёты", customer="C")
|
||||||
|
db.add(project)
|
||||||
|
db.flush()
|
||||||
|
system = boq.System(project_id=project.id, name="Система", code="S", sort_order=1)
|
||||||
|
db.add(system)
|
||||||
|
db.flush()
|
||||||
|
section = boq.Section(system_id=system.id, name="Раздел")
|
||||||
|
db.add(section)
|
||||||
|
db.flush()
|
||||||
|
doc = boq.BoqDocument(project_id=project.id, name="BOQ")
|
||||||
|
db.add(doc)
|
||||||
|
db.flush()
|
||||||
|
wi = boq.WorkItem(
|
||||||
|
project_id=project.id, boq_document_id=doc.id,
|
||||||
|
system_id=system.id, section_id=section.id,
|
||||||
|
source_number="1", name="Монтаж", unit="м",
|
||||||
|
quantity=Decimal("100"), unit_price=Decimal("10"), amount=Decimal("1000"),
|
||||||
|
)
|
||||||
|
db.add(wi)
|
||||||
|
db.commit()
|
||||||
|
report_id = None
|
||||||
|
if with_report:
|
||||||
|
report = DailyReport(project_id=project.id, system_id=system.id,
|
||||||
|
report_date=datetime.date(2026, 3, 1),
|
||||||
|
notes="смена")
|
||||||
|
db.add(report)
|
||||||
|
db.flush()
|
||||||
|
report.items.append(DailyReportItem(work_item_id=wi.id, completed_quantity=Decimal("5")))
|
||||||
|
db.commit()
|
||||||
|
report_id = report.id
|
||||||
|
return {"engine": engine, "pid": project.id, "wi": wi.id, "report_id": report_id,
|
||||||
|
"system_id": system.id, "storage": storage}
|
||||||
|
|
||||||
|
|
||||||
|
# ==========================================================================
|
||||||
|
# 1. Создание с фото и без
|
||||||
|
# ==========================================================================
|
||||||
|
|
||||||
|
def test_create_report_with_multiple_photos(tmp_path):
|
||||||
|
env = _seed(tmp_path)
|
||||||
|
_override(project_router.get_db, dr_router.get_db)
|
||||||
|
try:
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = _post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports",
|
||||||
|
data={"report_date": "2026-03-02", "system_id": str(env["system_id"]),
|
||||||
|
"notes": "с фото", f"quantity_{env['wi']}": "3"},
|
||||||
|
files=[
|
||||||
|
("files", ("a.jpg", JPG_BYTES, "image/jpeg")),
|
||||||
|
("files", ("b.png", PNG_BYTES, "image/png")),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
assert resp.status_code == 303, resp.text
|
||||||
|
report_id = int(resp.headers["location"].rsplit("/", 1)[-1])
|
||||||
|
with TestingSession() as db:
|
||||||
|
photos = db.query(DailyReportPhoto).filter_by(daily_report_id=report_id).all()
|
||||||
|
assert len(photos) == 2
|
||||||
|
for p in photos:
|
||||||
|
assert p.file_size > 0
|
||||||
|
assert p.content_type in ("image/jpeg", "image/png")
|
||||||
|
assert len(p.content_hash) == 64
|
||||||
|
# Файл действительно существует в storage
|
||||||
|
path = resolve_photo_path(p.storage_key)
|
||||||
|
assert path.is_file()
|
||||||
|
# original_name сохраняется только как подпись
|
||||||
|
names = {p.original_name for p in photos}
|
||||||
|
assert names == {"a.jpg", "b.png"}
|
||||||
|
view = client.get(f"/projects/{env['pid']}/daily-reports/{report_id}")
|
||||||
|
assert view.status_code == 200
|
||||||
|
assert "Фотоотчёт" in view.text
|
||||||
|
assert "a.jpg" in view.text or "b.png" in view.text
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
env["engine"].dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_report_without_photos(tmp_path):
|
||||||
|
env = _seed(tmp_path, with_report=False)
|
||||||
|
_override(project_router.get_db, dr_router.get_db)
|
||||||
|
try:
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = _post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports",
|
||||||
|
data={"report_date": "2026-03-03", "system_id": str(env["system_id"]),
|
||||||
|
"notes": "без фото", f"quantity_{env['wi']}": "2"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 303
|
||||||
|
report_id = int(resp.headers["location"].rsplit("/", 1)[-1])
|
||||||
|
with TestingSession() as db:
|
||||||
|
assert db.query(DailyReportPhoto).filter_by(daily_report_id=report_id).count() == 0
|
||||||
|
view = client.get(f"/projects/{env['pid']}/daily-reports/{report_id}")
|
||||||
|
assert "Фотографии не прикреплены" in view.text
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
env["engine"].dispose()
|
||||||
|
|
||||||
|
|
||||||
|
# ==========================================================================
|
||||||
|
# 2. Редактирование: просмотр, добавление, явное удаление
|
||||||
|
# ==========================================================================
|
||||||
|
|
||||||
|
def test_edit_add_and_explicitly_delete_photos(tmp_path):
|
||||||
|
env = _seed(tmp_path)
|
||||||
|
_override(project_router.get_db, dr_router.get_db)
|
||||||
|
try:
|
||||||
|
with TestClient(app) as client:
|
||||||
|
# Add one photo first
|
||||||
|
_post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports/{env['report_id']}/edit",
|
||||||
|
data={"report_date": "2026-03-01", "system_id": str(env["system_id"]),
|
||||||
|
"notes": "смена", f"quantity_{env['wi']}": "5"},
|
||||||
|
files=[("files", ("first.jpg", JPG_BYTES, "image/jpeg"))],
|
||||||
|
)
|
||||||
|
with TestingSession() as db:
|
||||||
|
first = db.query(DailyReportPhoto).one()
|
||||||
|
first_id = first.id
|
||||||
|
first_key = first.storage_key
|
||||||
|
|
||||||
|
# Edit form shows the saved photo with an explicit delete control
|
||||||
|
edit = client.get(f"/projects/{env['pid']}/daily-reports/{env['report_id']}/edit")
|
||||||
|
assert edit.status_code == 200
|
||||||
|
assert f'name="delete_photo_{first_id}"' in edit.text
|
||||||
|
assert "Сохранённые фотографии" in edit.text
|
||||||
|
|
||||||
|
# Add a second photo, keep the first (no delete checked)
|
||||||
|
_post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports/{env['report_id']}/edit",
|
||||||
|
data={"report_date": "2026-03-01", "system_id": str(env["system_id"]),
|
||||||
|
"notes": "смена", f"quantity_{env['wi']}": "5"},
|
||||||
|
files=[("files", ("second.png", PNG_BYTES, "image/png"))],
|
||||||
|
)
|
||||||
|
with TestingSession() as db:
|
||||||
|
assert db.query(DailyReportPhoto).count() == 2
|
||||||
|
|
||||||
|
# Explicit delete of the first photo only
|
||||||
|
resp = _post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports/{env['report_id']}/edit",
|
||||||
|
data={"report_date": "2026-03-01", "system_id": str(env["system_id"]),
|
||||||
|
"notes": "смена", f"quantity_{env['wi']}": "5",
|
||||||
|
f"delete_photo_{first_id}": "1"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 303
|
||||||
|
with TestingSession() as db:
|
||||||
|
remaining = db.query(DailyReportPhoto).all()
|
||||||
|
assert len(remaining) == 1
|
||||||
|
assert remaining[0].id != first_id
|
||||||
|
# Файл удалён из storage
|
||||||
|
assert not resolve_photo_path(first_key).exists()
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
env["engine"].dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_photo_delete_endpoint_is_explicit(tmp_path):
|
||||||
|
env = _seed(tmp_path)
|
||||||
|
_override(project_router.get_db, dr_router.get_db)
|
||||||
|
try:
|
||||||
|
with TestClient(app) as client:
|
||||||
|
_post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports/{env['report_id']}/edit",
|
||||||
|
data={"report_date": "2026-03-01", "system_id": str(env["system_id"]),
|
||||||
|
"notes": "смена", f"quantity_{env['wi']}": "5"},
|
||||||
|
files=[("files", ("x.jpg", JPG_BYTES, "image/jpeg"))],
|
||||||
|
)
|
||||||
|
with TestingSession() as db:
|
||||||
|
photo = db.query(DailyReportPhoto).one()
|
||||||
|
pid = photo.id
|
||||||
|
key = photo.storage_key
|
||||||
|
resp = _post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports/{env['report_id']}/photos/{pid}/delete"
|
||||||
|
)
|
||||||
|
assert resp.status_code == 303
|
||||||
|
with TestingSession() as db:
|
||||||
|
assert db.query(DailyReportPhoto).count() == 0
|
||||||
|
assert not resolve_photo_path(key).exists()
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
env["engine"].dispose()
|
||||||
|
|
||||||
|
|
||||||
|
# ==========================================================================
|
||||||
|
# 3. Некорректные / неподдерживаемые файлы
|
||||||
|
# ==========================================================================
|
||||||
|
|
||||||
|
def test_unsupported_file_rejected_and_form_data_preserved(tmp_path):
|
||||||
|
env = _seed(tmp_path, with_report=False)
|
||||||
|
_override(project_router.get_db, dr_router.get_db)
|
||||||
|
try:
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = _post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports",
|
||||||
|
data={"report_date": "2026-03-05", "system_id": str(env["system_id"]),
|
||||||
|
"notes": "важная заметка", f"quantity_{env['wi']}": "7"},
|
||||||
|
files=[("files", ("evil.exe", b"MZ\x90\x00" + b"\x00" * 32, "application/octet-stream"))],
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
html = resp.text
|
||||||
|
assert "Неподдерживаемый формат" in html
|
||||||
|
# Данные отчёта не потеряны
|
||||||
|
assert 'name="report_date"' in html and 'value="2026-03-05"' in html
|
||||||
|
assert 'value="важная заметка"' in html
|
||||||
|
assert f'name="quantity_{env["wi"]}"' in html
|
||||||
|
# Отчёт не создан
|
||||||
|
with TestingSession() as db:
|
||||||
|
assert db.query(DailyReport).count() == 0
|
||||||
|
assert db.query(DailyReportPhoto).count() == 0
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
env["engine"].dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_oversized_file_rejected(tmp_path):
|
||||||
|
env = _seed(tmp_path, with_report=False)
|
||||||
|
_override(project_router.get_db, dr_router.get_db)
|
||||||
|
try:
|
||||||
|
huge = JPG_BYTES + b"\x00" * (MAX_PHOTO_BYTES + 100)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = _post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports",
|
||||||
|
data={"report_date": "2026-03-05", "system_id": str(env["system_id"]),
|
||||||
|
"notes": "", f"quantity_{env['wi']}": "1"},
|
||||||
|
files=[("files", ("big.jpg", huge, "image/jpeg"))],
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "слишком большой" in resp.text
|
||||||
|
with TestingSession() as db:
|
||||||
|
assert db.query(DailyReportPhoto).count() == 0
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
env["engine"].dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_renamed_non_image_rejected(tmp_path):
|
||||||
|
"""Расширение .jpg не спасает файл без JPEG magic bytes."""
|
||||||
|
with pytest.raises(PhotoValidationError):
|
||||||
|
validate_upload(b"not an image at all", "fake.jpg", "image/jpeg")
|
||||||
|
|
||||||
|
|
||||||
|
def test_extension_content_mismatch_rejected():
|
||||||
|
with pytest.raises(PhotoValidationError):
|
||||||
|
validate_upload(PNG_BYTES, "photo.jpg", "image/png")
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_accepts_jpeg_png_webp():
|
||||||
|
assert validate_upload(JPG_BYTES, "a.jpg", "image/jpeg") == (".jpg", "image/jpeg")
|
||||||
|
assert validate_upload(JPG_BYTES, "a.jpeg", "image/jpeg") == (".jpg", "image/jpeg")
|
||||||
|
assert validate_upload(PNG_BYTES, "b.png", "image/png") == (".png", "image/png")
|
||||||
|
assert validate_upload(WEBP_BYTES, "c.webp", "image/webp") == (".webp", "image/webp")
|
||||||
|
|
||||||
|
|
||||||
|
# ==========================================================================
|
||||||
|
# 4. Безопасное формирование storage path
|
||||||
|
# ==========================================================================
|
||||||
|
|
||||||
|
def test_storage_key_is_server_generated_and_safe():
|
||||||
|
key = build_photo_storage_key(7, 11, ".jpg")
|
||||||
|
assert key == f"projects/7/daily_reports/11/photos/{key.rsplit('/', 1)[-1]}"
|
||||||
|
assert ".." not in key
|
||||||
|
assert not key.startswith("/")
|
||||||
|
assert "jpg" in key
|
||||||
|
path = resolve_photo_path(key)
|
||||||
|
assert "projects" in path.parts
|
||||||
|
|
||||||
|
|
||||||
|
def test_storage_key_rejects_traversal_and_bad_extension():
|
||||||
|
from app.services.daily_report_photo_service import PhotoPathError
|
||||||
|
with pytest.raises(PhotoPathError):
|
||||||
|
build_photo_storage_key(-1, 5, ".jpg")
|
||||||
|
with pytest.raises(PhotoPathError):
|
||||||
|
build_photo_storage_key(1, -2, ".jpg")
|
||||||
|
with pytest.raises(PhotoPathError):
|
||||||
|
build_photo_storage_key(1, 5, ".exe")
|
||||||
|
with pytest.raises(PhotoPathError):
|
||||||
|
build_photo_storage_key(1, 5, "..")
|
||||||
|
with pytest.raises(PhotoPathError):
|
||||||
|
resolve_photo_path("../../etc/passwd")
|
||||||
|
with pytest.raises(PhotoPathError):
|
||||||
|
resolve_photo_path("/etc/passwd")
|
||||||
|
with pytest.raises(PhotoPathError):
|
||||||
|
resolve_photo_path("projects/1/../../secret.jpg")
|
||||||
|
|
||||||
|
|
||||||
|
def test_original_name_never_used_as_path(tmp_path):
|
||||||
|
"""Даже вредоносное имя файла не влияет на storage_key."""
|
||||||
|
env = _seed(tmp_path, with_report=False)
|
||||||
|
try:
|
||||||
|
with TestingSession() as db:
|
||||||
|
photo = persist_photo(
|
||||||
|
db, project_id=env["pid"], daily_report_id=1,
|
||||||
|
content=JPG_BYTES,
|
||||||
|
original_name="../../evil/../payload.jpg",
|
||||||
|
content_type="image/jpeg",
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
assert ".." not in photo.storage_key
|
||||||
|
assert "evil" not in photo.storage_key
|
||||||
|
assert photo.original_name is None or ".." in photo.original_name
|
||||||
|
# original_name — только подпись, длина ограничена
|
||||||
|
assert len(photo.original_name or "") <= 255
|
||||||
|
finally:
|
||||||
|
env["engine"].dispose()
|
||||||
|
|
||||||
|
|
||||||
|
# ==========================================================================
|
||||||
|
# 5. Фото не теряются при редактировании объёмов / переключении систем
|
||||||
|
# ==========================================================================
|
||||||
|
|
||||||
|
def test_photos_survive_volume_edits_and_system_switch(tmp_path):
|
||||||
|
env = _seed(tmp_path)
|
||||||
|
_override(project_router.get_db, dr_router.get_db)
|
||||||
|
try:
|
||||||
|
with TestClient(app) as client:
|
||||||
|
_post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports/{env['report_id']}/edit",
|
||||||
|
data={"report_date": "2026-03-01", "system_id": str(env["system_id"]),
|
||||||
|
"notes": "смена", f"quantity_{env['wi']}": "5"},
|
||||||
|
files=[("files", ("keep.jpg", JPG_BYTES, "image/jpeg"))],
|
||||||
|
)
|
||||||
|
with TestingSession() as db:
|
||||||
|
before = db.query(DailyReportPhoto).count()
|
||||||
|
assert before == 1
|
||||||
|
|
||||||
|
# Меняем количество (12) и не трогаем фото
|
||||||
|
resp = _post(client,
|
||||||
|
f"/projects/{env['pid']}/daily-reports/{env['report_id']}/edit",
|
||||||
|
data={"report_date": "2026-03-01", "system_id": str(env["system_id"]),
|
||||||
|
"notes": "обновлено", f"quantity_{env['wi']}": "12"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 303
|
||||||
|
with TestingSession() as db:
|
||||||
|
report = db.query(DailyReport).one()
|
||||||
|
assert db.query(DailyReportPhoto).count() == 1
|
||||||
|
assert report.notes == "обновлено"
|
||||||
|
assert Decimal(str(report.items[0].completed_quantity)) == Decimal("12")
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
env["engine"].dispose()
|
||||||
|
|
||||||
|
|
||||||
|
# ==========================================================================
|
||||||
|
# 6. Экспорт / импорт проекта
|
||||||
|
# ==========================================================================
|
||||||
|
|
||||||
|
def _export_zip(pid, session_factory=None):
|
||||||
|
from app.exporters.project_export import export_project
|
||||||
|
factory = session_factory or TestingSession
|
||||||
|
with factory() as db:
|
||||||
|
return export_project(db, pid)
|
||||||
|
|
||||||
|
|
||||||
|
def test_export_import_roundtrip_preserves_photos(tmp_path):
|
||||||
|
env = _seed(tmp_path)
|
||||||
|
with TestingSession() as db:
|
||||||
|
report = db.query(DailyReport).one()
|
||||||
|
persist_photos(
|
||||||
|
db, project_id=env["pid"], daily_report_id=report.id,
|
||||||
|
uploads=[
|
||||||
|
(JPG_BYTES, "s1.jpg", "image/jpeg"),
|
||||||
|
(PNG_BYTES, "s2.png", "image/png"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
data, filename = _export_zip(env["pid"])
|
||||||
|
assert filename.endswith(".zip")
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||||||
|
names = zf.namelist()
|
||||||
|
assert "daily_report_photos.json" in names
|
||||||
|
photo_entries = [n for n in names if n.startswith("photos/")]
|
||||||
|
assert len(photo_entries) == 2
|
||||||
|
import json
|
||||||
|
rows = json.loads(zf.read("daily_report_photos.json").decode("utf-8"))
|
||||||
|
assert len(rows) == 2
|
||||||
|
for row in rows:
|
||||||
|
assert row["daily_report_export_id"].startswith("daily_report:")
|
||||||
|
assert row["content_hash"] and len(row["content_hash"]) == 64
|
||||||
|
assert row["archive_path"].startswith("photos/")
|
||||||
|
|
||||||
|
# Импорт в чистую БД
|
||||||
|
from app.exporters.project_import import import_project
|
||||||
|
engine2 = _engine()
|
||||||
|
Session2 = sessionmaker(bind=engine2, expire_on_commit=False)
|
||||||
|
try:
|
||||||
|
with Session2() as db2:
|
||||||
|
project2 = import_project(db2, data)
|
||||||
|
photos = db2.query(DailyReportPhoto).filter_by(project_id=project2.id).all()
|
||||||
|
assert len(photos) == 2
|
||||||
|
for p in photos:
|
||||||
|
path = resolve_photo_path(p.storage_key)
|
||||||
|
assert path.is_file()
|
||||||
|
content = path.read_bytes()
|
||||||
|
assert content in (JPG_BYTES, PNG_BYTES)
|
||||||
|
reports = db2.query(DailyReport).filter_by(project_id=project2.id).all()
|
||||||
|
assert len(reports) == 1
|
||||||
|
for p in photos:
|
||||||
|
assert p.daily_report_id == reports[0].id
|
||||||
|
|
||||||
|
# Повторный экспорт/импорт сохраняет фото и ссылки
|
||||||
|
data2, _ = _export_zip(project2.id, Session2)
|
||||||
|
engine3 = _engine()
|
||||||
|
Session3 = sessionmaker(bind=engine3, expire_on_commit=False)
|
||||||
|
try:
|
||||||
|
with Session3() as db3:
|
||||||
|
project3 = import_project(db3, data2)
|
||||||
|
photos3 = db3.query(DailyReportPhoto).filter_by(project_id=project3.id).all()
|
||||||
|
assert len(photos3) == 2
|
||||||
|
for p in photos3:
|
||||||
|
assert resolve_photo_path(p.storage_key).is_file()
|
||||||
|
finally:
|
||||||
|
engine3.dispose()
|
||||||
|
finally:
|
||||||
|
engine2.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_export_without_photos_still_valid(tmp_path):
|
||||||
|
env = _seed(tmp_path) # report without photos
|
||||||
|
data, _ = _export_zip(env["pid"])
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||||||
|
import json
|
||||||
|
rows = json.loads(zf.read("daily_report_photos.json").decode("utf-8"))
|
||||||
|
assert rows == []
|
||||||
|
assert not any(n.startswith("photos/") for n in zf.namelist())
|
||||||
|
from app.exporters.project_import import import_project
|
||||||
|
engine2 = _engine()
|
||||||
|
Session2 = sessionmaker(bind=engine2, expire_on_commit=False)
|
||||||
|
try:
|
||||||
|
with Session2() as db2:
|
||||||
|
project2 = import_project(db2, data)
|
||||||
|
assert db2.query(DailyReportPhoto).filter_by(project_id=project2.id).count() == 0
|
||||||
|
finally:
|
||||||
|
engine2.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
# ==========================================================================
|
||||||
|
# 7. Сброс базы чистит метаданные и файлы
|
||||||
|
# ==========================================================================
|
||||||
|
|
||||||
|
def test_database_reset_clears_photos_and_files(tmp_path):
|
||||||
|
env = _seed(tmp_path)
|
||||||
|
with TestingSession() as db:
|
||||||
|
report = db.query(DailyReport).one()
|
||||||
|
photo = persist_photo(
|
||||||
|
db, project_id=env["pid"], daily_report_id=report.id,
|
||||||
|
content=JPG_BYTES, original_name="r.jpg", content_type="image/jpeg",
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
key = photo.storage_key
|
||||||
|
assert resolve_photo_path(key).is_file()
|
||||||
|
|
||||||
|
from app.services.database_reset import reset_database
|
||||||
|
with TestingSession() as db:
|
||||||
|
result = reset_database(db)
|
||||||
|
assert result.deleted["daily_report_photos"] == 1
|
||||||
|
assert result.deleted["daily_reports"] == 1
|
||||||
|
assert result.storage_removed is True
|
||||||
|
assert not resolve_photo_path(key).exists()
|
||||||
|
with TestingSession() as db:
|
||||||
|
assert db.query(DailyReportPhoto).count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
# ==========================================================================
|
||||||
|
# 8. Финансовые документы не удаляют фото
|
||||||
|
# ==========================================================================
|
||||||
|
|
||||||
|
def test_ks2_storno_does_not_delete_photos(tmp_path):
|
||||||
|
env = _seed(tmp_path)
|
||||||
|
with TestingSession() as db:
|
||||||
|
report = db.query(DailyReport).one()
|
||||||
|
item = report.items[0]
|
||||||
|
photo = persist_photo(
|
||||||
|
db, project_id=env["pid"], daily_report_id=report.id,
|
||||||
|
content=PNG_BYTES, original_name="p.png", content_type="image/png",
|
||||||
|
)
|
||||||
|
db.flush()
|
||||||
|
ks2 = KS2(project_id=env["pid"], number="1", date=datetime.date(2026, 3, 10),
|
||||||
|
status="issued", reporting_period_from=datetime.date(2026, 3, 1),
|
||||||
|
reporting_period_to=datetime.date(2026, 3, 31))
|
||||||
|
db.add(ks2)
|
||||||
|
db.flush()
|
||||||
|
ks2_item = KS2Item(ks2_id=ks2.id, work_item_id=env["wi"],
|
||||||
|
quantity=Decimal("2"), unit_price=Decimal("10"),
|
||||||
|
amount=Decimal("20"))
|
||||||
|
db.add(ks2_item)
|
||||||
|
db.flush()
|
||||||
|
db.add(KS2ItemSource(ks2_item_id=ks2_item.id,
|
||||||
|
daily_report_item_id=item.id, quantity=Decimal("2")))
|
||||||
|
db.commit()
|
||||||
|
photo_id = photo.id
|
||||||
|
photo_key = photo.storage_key
|
||||||
|
|
||||||
|
# Сторнирование КС-2
|
||||||
|
with TestingSession() as db:
|
||||||
|
ks2 = db.query(KS2).one()
|
||||||
|
ks2.status = "cancelled"
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
with TestingSession() as db:
|
||||||
|
assert db.query(DailyReportPhoto).count() == 1
|
||||||
|
assert db.query(DailyReportPhoto).one().id == photo_id
|
||||||
|
assert resolve_photo_path(photo_key).is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def test_ks3_and_payment_storno_do_not_delete_photos(tmp_path):
|
||||||
|
env = _seed(tmp_path)
|
||||||
|
with TestingSession() as db:
|
||||||
|
report = db.query(DailyReport).one()
|
||||||
|
photo = persist_photo(
|
||||||
|
db, project_id=env["pid"], daily_report_id=report.id,
|
||||||
|
content=JPG_BYTES, original_name="q.jpg", content_type="image/jpeg",
|
||||||
|
)
|
||||||
|
db.flush()
|
||||||
|
ks2 = KS2(project_id=env["pid"], number="1", date=datetime.date(2026, 3, 10),
|
||||||
|
status="issued", reporting_period_from=datetime.date(2026, 3, 1),
|
||||||
|
reporting_period_to=datetime.date(2026, 3, 31))
|
||||||
|
db.add(ks2)
|
||||||
|
db.flush()
|
||||||
|
ks3 = KS3(project_id=env["pid"], number="1", date=datetime.date(2026, 3, 12),
|
||||||
|
status="issued", reporting_period_from=datetime.date(2026, 3, 1),
|
||||||
|
reporting_period_to=datetime.date(2026, 3, 31))
|
||||||
|
db.add(ks3)
|
||||||
|
db.flush()
|
||||||
|
db.add(KS3KS2(ks3_id=ks3.id, ks2_id=ks2.id))
|
||||||
|
pay = Payment(project_id=env["pid"], date=datetime.date(2026, 3, 15),
|
||||||
|
amount=Decimal("100"), status="active")
|
||||||
|
db.add(pay)
|
||||||
|
db.commit()
|
||||||
|
photo_key = photo.storage_key
|
||||||
|
|
||||||
|
with TestingSession() as db:
|
||||||
|
ks3 = db.query(KS3).one()
|
||||||
|
ks3.status = "cancelled"
|
||||||
|
pay = db.query(Payment).one()
|
||||||
|
pay.status = "cancelled"
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
with TestingSession() as db:
|
||||||
|
assert db.query(DailyReportPhoto).count() == 1
|
||||||
|
assert resolve_photo_path(photo_key).is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_report_cleans_photo_files(tmp_path):
|
||||||
|
env = _seed(tmp_path)
|
||||||
|
with TestingSession() as db:
|
||||||
|
report = db.query(DailyReport).one()
|
||||||
|
photo = persist_photo(
|
||||||
|
db, project_id=env["pid"], daily_report_id=report.id,
|
||||||
|
content=JPG_BYTES, original_name="d.jpg", content_type="image/jpeg",
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
key = photo.storage_key
|
||||||
|
assert resolve_photo_path(key).is_file()
|
||||||
|
|
||||||
|
_override(project_router.get_db, dr_router.get_db)
|
||||||
|
try:
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = _post(client, f"/projects/{env['pid']}/daily-reports/{env['report_id']}/delete")
|
||||||
|
assert resp.status_code == 303
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
with TestingSession() as db:
|
||||||
|
assert db.query(DailyReportPhoto).count() == 0
|
||||||
|
assert not resolve_photo_path(key).exists()
|
||||||
|
|
||||||
|
|
||||||
|
# ==========================================================================
|
||||||
|
# 11. Лёгкий сценарий: фото необязательны
|
||||||
|
# ==========================================================================
|
||||||
|
|
||||||
|
def test_photo_input_is_optional_on_the_form(tmp_path):
|
||||||
|
env = _seed(tmp_path)
|
||||||
|
_override(project_router.get_db, dr_router.get_db)
|
||||||
|
try:
|
||||||
|
with TestClient(app) as client:
|
||||||
|
page = client.get(f"/projects/{env['pid']}/daily-reports/{env['report_id']}/edit")
|
||||||
|
assert page.status_code == 200
|
||||||
|
# Поле файла есть, но не required — быстрый ввод объёмов не заблокирован
|
||||||
|
assert 'type="file"' in page.text
|
||||||
|
assert 'id="photo-input"' in page.text
|
||||||
|
assert 'required' not in page.text.split('id="photo-input"')[0][-200:] + \
|
||||||
|
page.text.split('id="photo-input"')[1][:120]
|
||||||
|
assert "Фотоотчёт" in page.text
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
env["engine"].dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_photo_limit_enforced(tmp_path):
|
||||||
|
env = _seed(tmp_path, with_report=False)
|
||||||
|
try:
|
||||||
|
with TestingSession() as db:
|
||||||
|
report = DailyReport(project_id=env["pid"], report_date=datetime.date(2026, 3, 1))
|
||||||
|
db.add(report)
|
||||||
|
db.flush()
|
||||||
|
uploads = [(JPG_BYTES, f"f{i}.jpg", "image/jpeg") for i in range(MAX_PHOTOS_PER_REPORT)]
|
||||||
|
persist_photos(db, project_id=env["pid"], daily_report_id=report.id, uploads=uploads)
|
||||||
|
db.commit()
|
||||||
|
with pytest.raises(PhotoValidationError, match="максимальное количество"):
|
||||||
|
persist_photo(
|
||||||
|
db, project_id=env["pid"], daily_report_id=report.id,
|
||||||
|
content=JPG_BYTES, original_name="extra.jpg", content_type="image/jpeg",
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
env["engine"].dispose()
|
||||||
Reference in New Issue
Block a user