feat: add photos to daily reports
This commit is contained in:
@@ -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