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"
|
||||
AGREEMENT_STATUS_CANCELLED_MIGRATION = "20260930_agreement_status_cancelled"
|
||||
PROJECT_REQUISITES_MIGRATION = "20260930_project_requisites"
|
||||
DAILY_REPORT_PHOTOS_MIGRATION = "20261015_daily_report_photos"
|
||||
|
||||
|
||||
def run_migrations(engine):
|
||||
@@ -308,6 +309,32 @@ def run_migrations(engine):
|
||||
)
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(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()
|
||||
if violations:
|
||||
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.boq import BoqDocument, Section, System, WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.daily_report_photo import DailyReportPhoto
|
||||
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||
from app.models.ks3 import KS3, KS3KS2
|
||||
from app.models.payment import Payment, PaymentAllocation
|
||||
@@ -46,8 +47,12 @@ REQUIRED_FILES = (
|
||||
"checksums.json",
|
||||
)
|
||||
|
||||
# Old Task 025 archives may lack this file; import treats it as an empty journal.
|
||||
OPTIONAL_FILES = ("work_journal_entries.json", "document_artifacts.json")
|
||||
# Old Task 025 archives may lack these files; import treats them as empty.
|
||||
OPTIONAL_FILES = (
|
||||
"work_journal_entries.json",
|
||||
"document_artifacts.json",
|
||||
"daily_report_photos.json",
|
||||
)
|
||||
EXPORT_FILES = REQUIRED_FILES[:-1] + OPTIONAL_FILES + ("checksums.json",)
|
||||
|
||||
|
||||
@@ -198,6 +203,13 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
|
||||
.order_by(DocumentArtifact.id)
|
||||
.all()
|
||||
)
|
||||
# Daily Report photos belong to the primary report and travel with it.
|
||||
daily_report_photos = (
|
||||
db.query(DailyReportPhoto)
|
||||
.filter(DailyReportPhoto.project_id == project_id)
|
||||
.order_by(DailyReportPhoto.id)
|
||||
.all()
|
||||
)
|
||||
|
||||
return {
|
||||
"project": project,
|
||||
@@ -209,6 +221,7 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
|
||||
"agreement_items": agreement_items,
|
||||
"daily_reports": daily_reports,
|
||||
"daily_report_items": daily_report_items,
|
||||
"daily_report_photos": daily_report_photos,
|
||||
"ks2": ks2_docs,
|
||||
"ks2_items": ks2_items,
|
||||
"ks2_item_sources": ks2_item_sources,
|
||||
@@ -291,6 +304,11 @@ def _validate_graph(graph: dict[str, Any]) -> None:
|
||||
errors.append(f"daily_report_item:{i.id} references missing daily_report")
|
||||
if i.work_item_id not in work_item_ids:
|
||||
errors.append(f"daily_report_item:{i.id} references missing work_item")
|
||||
for p in graph.get("daily_report_photos", []):
|
||||
if p.daily_report_id not in report_ids:
|
||||
errors.append(f"daily_report_photo:{p.id} references missing daily_report")
|
||||
if p.project_id != pid:
|
||||
errors.append(f"daily_report_photo:{p.id} belongs to another project")
|
||||
for k in graph["ks2"]:
|
||||
if k.project_id != pid:
|
||||
errors.append(f"ks2:{k.id} belongs to another project")
|
||||
@@ -347,6 +365,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
|
||||
"agreement_item": _key_map(graph["agreement_items"], "agreement_item"),
|
||||
"daily_report": _key_map(graph["daily_reports"], "daily_report"),
|
||||
"daily_report_item": _key_map(graph["daily_report_items"], "daily_report_item"),
|
||||
"daily_report_photo": _key_map(graph.get("daily_report_photos", []), "daily_report_photo"),
|
||||
"ks2": _key_map(graph["ks2"], "ks2"),
|
||||
"ks2_item": _key_map(graph["ks2_items"], "ks2_item"),
|
||||
"ks2_item_source": _key_map(graph["ks2_item_sources"], "ks2_item_source"),
|
||||
@@ -526,6 +545,38 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
|
||||
)
|
||||
for i in graph["daily_report_items"]
|
||||
]
|
||||
daily_report_photo_records = []
|
||||
photo_blobs: dict[str, bytes] = {}
|
||||
for photo in graph.get("daily_report_photos", []):
|
||||
photo_export_id = ref("daily_report", photo.daily_report_id)
|
||||
if photo_export_id is None:
|
||||
raise ProjectExportError(
|
||||
f"Photo {photo.id} references unknown DailyReport {photo.daily_report_id}"
|
||||
)
|
||||
try:
|
||||
from app.services.daily_report_photo_service import (
|
||||
photo_file_bytes,
|
||||
)
|
||||
file_bytes = photo_file_bytes(photo)
|
||||
except Exception as exc:
|
||||
raise ProjectExportError(
|
||||
f"Photo file missing for daily_report_photo:{photo.id} "
|
||||
f"({photo.storage_key})"
|
||||
) from exc
|
||||
archive_path = f"photos/{photo_export_id.replace(':', '_')}/{photo.id:08d}.bin"
|
||||
photo_blobs[archive_path] = file_bytes
|
||||
daily_report_photo_records.append({
|
||||
"export_id": f"daily_report_photo:{photo.id:08d}",
|
||||
"source_id": photo.id,
|
||||
"daily_report_export_id": photo_export_id,
|
||||
"original_name": photo.original_name,
|
||||
"content_type": photo.content_type,
|
||||
"file_size": photo.file_size,
|
||||
"content_hash": photo.content_hash,
|
||||
"sort_order": photo.sort_order,
|
||||
"created_at": _iso(photo.created_at),
|
||||
"archive_path": archive_path,
|
||||
})
|
||||
ks2 = [
|
||||
record(
|
||||
"ks2",
|
||||
@@ -710,6 +761,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
|
||||
"agreement_items": len(agreement_items),
|
||||
"daily_reports": len(daily_reports),
|
||||
"daily_report_items": len(daily_report_items),
|
||||
"daily_report_photos": len(daily_report_photo_records),
|
||||
"ks2": len(ks2),
|
||||
"ks2_items": len(ks2_items),
|
||||
"ks2_item_sources": len(ks2_item_sources),
|
||||
@@ -740,6 +792,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
|
||||
"agreement_items.json": agreement_items,
|
||||
"daily_reports.json": daily_reports,
|
||||
"daily_report_items.json": daily_report_items,
|
||||
"daily_report_photos.json": daily_report_photo_records,
|
||||
"ks2.json": ks2,
|
||||
"ks2_items.json": ks2_items,
|
||||
"ks2_item_sources.json": ks2_item_sources,
|
||||
@@ -750,6 +803,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
|
||||
"work_journal_entries.json": work_journal_entries,
|
||||
"document_artifacts.json": document_artifacts_records,
|
||||
}
|
||||
artifact_blobs.update(photo_blobs)
|
||||
return {**files, "__artifact_blobs__": artifact_blobs}
|
||||
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ _LIST_FILES = (
|
||||
"payment_allocations.json",
|
||||
"work_journal_entries.json",
|
||||
"document_artifacts.json",
|
||||
"daily_report_photos.json",
|
||||
)
|
||||
|
||||
_ALLOWED_AGREEMENT_STATUS = {"draft", "approved", "cancelled"}
|
||||
@@ -78,6 +79,7 @@ _REQUIRED_FIELDS: dict[str, tuple[str, ...]] = {
|
||||
"payment_allocations.json": ("export_id", "payment_export_id", "ks3_export_id", "amount"),
|
||||
"work_journal_entries.json": ("export_id", "type", "text"),
|
||||
"document_artifacts.json": ("export_id", "document_type", "document_export_id", "format", "content_hash", "archive_path"),
|
||||
"daily_report_photos.json": ("export_id", "daily_report_export_id", "content_type", "file_size", "content_hash", "archive_path"),
|
||||
}
|
||||
|
||||
|
||||
@@ -148,6 +150,11 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
for name in names:
|
||||
if name.startswith("artifacts/") and not name.endswith("/"):
|
||||
artifact_files[name] = zf.read(name)
|
||||
# Daily Report photo files (any path under photos/)
|
||||
photo_files: dict[str, bytes] = {}
|
||||
for name in names:
|
||||
if name.startswith("photos/") and not name.endswith("/"):
|
||||
photo_files[name] = zf.read(name)
|
||||
|
||||
try:
|
||||
checksums = json.loads(raw["checksums.json"].decode("utf-8"))
|
||||
@@ -171,6 +178,13 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
if expected != actual:
|
||||
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
|
||||
|
||||
# Validate photo file checksums too
|
||||
for name, body in photo_files.items():
|
||||
expected = checksums.get(name)
|
||||
actual = _sha256(body)
|
||||
if expected != actual:
|
||||
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
|
||||
|
||||
payload: dict[str, Any] = {}
|
||||
for name, body in raw.items():
|
||||
if name == "checksums.json":
|
||||
@@ -191,6 +205,11 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
payload["document_artifacts.json"] = []
|
||||
missing_optional.add("document_artifacts.json")
|
||||
|
||||
# Backward compatibility: old archives have no Daily Report photos.
|
||||
if "daily_report_photos.json" not in payload:
|
||||
payload["daily_report_photos.json"] = []
|
||||
missing_optional.add("daily_report_photos.json")
|
||||
|
||||
manifest = payload.get("manifest.json")
|
||||
if not isinstance(manifest, dict):
|
||||
raise ProjectImportError("manifest.json: ожидается объект")
|
||||
@@ -208,7 +227,7 @@ def _read_archive(data: bytes) -> dict[str, Any]:
|
||||
raise ProjectImportError(f"{name}: ожидается массив")
|
||||
|
||||
return {"payload": payload, "manifest": manifest, "missing_optional": missing_optional,
|
||||
"artifact_files": artifact_files}
|
||||
"artifact_files": artifact_files, "photo_files": photo_files}
|
||||
|
||||
|
||||
def _validate_records(
|
||||
@@ -397,6 +416,17 @@ def _validate_records(
|
||||
raise ProjectImportError("daily_report_items: битая ссылка на daily_report")
|
||||
if not has("work_items.json", row["work_item_export_id"]):
|
||||
raise ProjectImportError("daily_report_items: битая ссылка на work_item")
|
||||
for idx, row in enumerate(payload.get("daily_report_photos.json", []), 1):
|
||||
for field in _REQUIRED_FIELDS["daily_report_photos.json"]:
|
||||
if field not in row:
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: нет поля {field}")
|
||||
if not has("daily_reports.json", row["daily_report_export_id"]):
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: битая ссылка на daily_report")
|
||||
if not isinstance(row["file_size"], int) or row["file_size"] <= 0:
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: file_size должен быть положительным числом")
|
||||
h = row["content_hash"]
|
||||
if not isinstance(h, str) or len(h) != 64:
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: content_hash должен быть SHA-256 (64 символа)")
|
||||
for row in payload["ks2_items.json"]:
|
||||
if not has("ks2.json", row["ks2_export_id"]):
|
||||
raise ProjectImportError("ks2_items: битая ссылка на ks2")
|
||||
@@ -458,6 +488,35 @@ def validate_archive(data: bytes) -> dict[str, Any]:
|
||||
if ap not in art_paths:
|
||||
raise ProjectImportError(f"Orphan artifact file in archive: {ap}")
|
||||
|
||||
# Validate photo files against daily_report_photos.json
|
||||
photo_files = result.get("photo_files", {})
|
||||
photo_rows = payload.get("daily_report_photos.json", [])
|
||||
photo_paths = {r["archive_path"] for r in photo_rows}
|
||||
from app.services.daily_report_photo_service import (
|
||||
ALLOWED_CONTENT_TYPES,
|
||||
MAX_PHOTO_BYTES,
|
||||
compute_content_hash as photo_hash,
|
||||
)
|
||||
for idx, row in enumerate(photo_rows, 1):
|
||||
ap = row["archive_path"]
|
||||
if not isinstance(ap, str) or not ap.startswith("photos/") or ".." in ap.split("/") or ap.startswith("/"):
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: небезопасный archive_path")
|
||||
if ap not in photo_files:
|
||||
raise ProjectImportError(f"Photo file missing in archive: {ap}")
|
||||
body = photo_files[ap]
|
||||
if len(body) > MAX_PHOTO_BYTES:
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: файл превышает лимит размера")
|
||||
if photo_hash(body) != row["content_hash"]:
|
||||
raise ProjectImportError(f"Photo hash mismatch for {ap}")
|
||||
if int(row.get("file_size") or 0) != len(body):
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: file_size не совпадает с содержимым")
|
||||
if row["content_type"] not in ALLOWED_CONTENT_TYPES:
|
||||
raise ProjectImportError(f"daily_report_photos[{idx}]: недопустимый content_type")
|
||||
# No orphan photo files
|
||||
for ap in photo_files:
|
||||
if ap not in photo_paths:
|
||||
raise ProjectImportError(f"Orphan photo file in archive: {ap}")
|
||||
|
||||
counts = dict(manifest.get("counts") or {})
|
||||
if "work_journal_entries.json" in result.get("missing_optional", set()):
|
||||
counts["work_journal_entries"] = 0
|
||||
@@ -467,6 +526,10 @@ def validate_archive(data: bytes) -> dict[str, Any]:
|
||||
counts["document_artifacts"] = 0
|
||||
else:
|
||||
counts.setdefault("document_artifacts", len(art_rows))
|
||||
if "daily_report_photos.json" in result.get("missing_optional", set()):
|
||||
counts["daily_report_photos"] = 0
|
||||
else:
|
||||
counts.setdefault("daily_report_photos", len(photo_rows))
|
||||
return {
|
||||
"manifest": manifest,
|
||||
"project_name": payload["project.json"].get("name"),
|
||||
@@ -474,6 +537,7 @@ def validate_archive(data: bytes) -> dict[str, Any]:
|
||||
"counts": counts,
|
||||
"payload": payload,
|
||||
"artifact_files": artifact_files,
|
||||
"photo_files": photo_files,
|
||||
}
|
||||
|
||||
|
||||
@@ -790,6 +854,58 @@ def _import_entities(db: Session, payload: dict[str, Any]) -> Project:
|
||||
pass
|
||||
raise
|
||||
|
||||
# Restore Daily Report photos (primary report attachments)
|
||||
created_photo_paths: list = []
|
||||
try:
|
||||
from app.services.daily_report_photo_service import (
|
||||
build_photo_storage_key,
|
||||
resolve_photo_path,
|
||||
)
|
||||
|
||||
photo_files = payload.get("__photo_files__", {})
|
||||
for row in payload.get("daily_report_photos.json", []):
|
||||
new_report_id = _require_mapping(
|
||||
row["daily_report_export_id"], ids, "daily_report_export_id"
|
||||
)
|
||||
# Extension comes from validated content_type, never from the archive name.
|
||||
ext_by_type = {"image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp"}
|
||||
ext = ext_by_type[row["content_type"]]
|
||||
storage_key = build_photo_storage_key(
|
||||
project.id, new_report_id, ext,
|
||||
)
|
||||
file_bytes = photo_files.get(row["archive_path"])
|
||||
if file_bytes is None:
|
||||
raise ProjectImportError(
|
||||
f"Photo file missing in archive: {row['archive_path']}"
|
||||
)
|
||||
dest = resolve_photo_path(storage_key)
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(file_bytes)
|
||||
created_photo_paths.append(dest)
|
||||
|
||||
from app.models.daily_report_photo import DailyReportPhoto
|
||||
photo = DailyReportPhoto(
|
||||
project_id=project.id,
|
||||
daily_report_id=new_report_id,
|
||||
storage_key=storage_key,
|
||||
original_name=row.get("original_name"),
|
||||
content_type=row["content_type"],
|
||||
file_size=int(row["file_size"]),
|
||||
content_hash=row["content_hash"],
|
||||
sort_order=int(row.get("sort_order") or 0),
|
||||
)
|
||||
db.add(photo)
|
||||
db.flush()
|
||||
ids[row["export_id"]] = photo.id
|
||||
except Exception:
|
||||
for p in created_photo_paths:
|
||||
try:
|
||||
if p.is_file():
|
||||
p.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
db.flush()
|
||||
return project
|
||||
|
||||
@@ -799,6 +915,7 @@ def import_project(db: Session, data: bytes) -> Project:
|
||||
preview = validate_archive(data)
|
||||
payload = preview["payload"]
|
||||
payload["__artifact_files__"] = preview.get("artifact_files", {})
|
||||
payload["__photo_files__"] = preview.get("photo_files", {})
|
||||
try:
|
||||
project = _import_entities(db, payload)
|
||||
db.commit()
|
||||
|
||||
@@ -10,6 +10,7 @@ from app.routers import projects, boq as boq_router, daily_reports, agreements,
|
||||
# Import models to ensure they're registered
|
||||
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_photo as daily_report_photo_models
|
||||
from app.models import work_journal as work_journal_models
|
||||
from app.models import agreement as agreement_models
|
||||
from app.models import ks2 as ks2_models
|
||||
|
||||
@@ -19,6 +19,7 @@ class DailyReport(Base):
|
||||
project = relationship("Project")
|
||||
system = relationship("System")
|
||||
items = relationship("DailyReportItem", back_populates="report", cascade="all, delete-orphan")
|
||||
photos = relationship("DailyReportPhoto", back_populates="report", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
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})>"
|
||||
)
|
||||
+212
-14
@@ -1,8 +1,8 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import RedirectResponse, Response
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -20,6 +20,17 @@ from app.services.daily_report_service import (
|
||||
has_closed_volume,
|
||||
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
|
||||
|
||||
router = APIRouter()
|
||||
@@ -72,7 +83,8 @@ def _report_rows(db: Session, project_id: int, system_id: int | None, exclude_re
|
||||
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"]
|
||||
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]
|
||||
@@ -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.
|
||||
rows = _report_rows(db, project_obj.id, selected_id, report.id if report else None,
|
||||
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:
|
||||
row["current_quantity"] = current.get(row["item"].id)
|
||||
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
|
||||
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", {
|
||||
"request": request, "project": project_obj, "systems": systems,
|
||||
"has_unclassified_items": bool(unclassified), "unclassified_selected": unclassified_selected,
|
||||
"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):
|
||||
@@ -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)
|
||||
|
||||
|
||||
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")
|
||||
async def create_daily_report(request: Request, project_id: int,
|
||||
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)
|
||||
try:
|
||||
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
|
||||
system_id = _parse_system_selection(db, project_id, system_id)
|
||||
form = await request.form()
|
||||
form_values = {k: v for k, v in form.multi_items() if k != "files"}
|
||||
quantities, errors = _quantities_from_form(form)
|
||||
uploads = _collect_uploads(files)
|
||||
errors.extend(_validate_uploads(uploads))
|
||||
selection = "unclassified" if system_id is None else system_id
|
||||
# Nothing is written yet: the user keeps every already-entered field.
|
||||
if errors:
|
||||
selection = "unclassified" if system_id is None else system_id
|
||||
return _render_form(request, db, project_obj, selection, errors=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)
|
||||
report = DailyReport(project_id=project_id, system_id=system_id, report_date=parsed_date,
|
||||
notes=notes.strip() or None)
|
||||
for item_id, quantity in quantities.items():
|
||||
report.items.append(DailyReportItem(work_item_id=item_id, completed_quantity=quantity))
|
||||
db.add(report)
|
||||
db.commit()
|
||||
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()
|
||||
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)
|
||||
|
||||
|
||||
@@ -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"]
|
||||
can_del, del_reason = can_delete_report(db, report)
|
||||
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", {
|
||||
"request": request, "project": project_obj, "report": report,
|
||||
"rows": displayed, "warnings": warnings, "system_names": system_names,
|
||||
"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")
|
||||
async def update_daily_report(request: Request, project_id: int, report_id: int,
|
||||
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)
|
||||
report = _report_or_404(db, project_id, report_id)
|
||||
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
|
||||
system_id = _parse_system_selection(db, project_id, system_id)
|
||||
form = await request.form()
|
||||
form_values = {k: v for k, v in form.multi_items() if k != "files"}
|
||||
quantities, errors = _quantities_from_form(form)
|
||||
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
|
||||
# Nothing is written yet: the user keeps every already-entered field.
|
||||
if errors:
|
||||
selection = "unclassified" if system_id is None else system_id
|
||||
return _render_form(request, db, project_obj, selection, report, 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)
|
||||
try:
|
||||
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,
|
||||
)
|
||||
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)
|
||||
|
||||
|
||||
@@ -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)):
|
||||
_project_or_404(db, project_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:
|
||||
delete_report(db, report)
|
||||
except DailyReportError as 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)
|
||||
|
||||
|
||||
@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")
|
||||
async def delete_daily_report_item(
|
||||
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.boq import BoqDocument, Section, System, WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.daily_report_photo import DailyReportPhoto
|
||||
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||
from app.models.ks3 import KS3, KS3KS2
|
||||
from app.models.payment import Payment, PaymentAllocation
|
||||
@@ -38,6 +39,7 @@ DELETE_ORDER = (
|
||||
("ks2_item_sources", KS2ItemSource),
|
||||
("ks2_items", KS2Item),
|
||||
("ks2_documents", KS2),
|
||||
("daily_report_photos", DailyReportPhoto),
|
||||
("daily_report_items", DailyReportItem),
|
||||
("daily_reports", DailyReport),
|
||||
("agreement_items", AgreementItem),
|
||||
|
||||
@@ -18,12 +18,13 @@
|
||||
<h1>{{ 'Редактировать Daily Report' if report else 'Новый Daily Report' }}</h1>
|
||||
{% 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 '') }}">
|
||||
<div class="card card-body mb-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-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-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="{{ form_values.get('notes', report.notes if report and report.notes else '') }}"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -88,6 +89,50 @@
|
||||
</table>
|
||||
</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">
|
||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/daily-reports">Отмена</a>
|
||||
<button class="btn btn-primary" type="submit">{{ 'Сохранить изменения' if report else 'Создать отчёт' }}</button>
|
||||
@@ -213,6 +258,51 @@
|
||||
|
||||
rebuildSelected();
|
||||
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>
|
||||
</main>
|
||||
|
||||
@@ -46,6 +46,37 @@
|
||||
</tr>
|
||||
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">В отчёте нет рабочих позиций.</td></tr>{% endfor %}</tbody>
|
||||
</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>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
Reference in New Issue
Block a user