from pathlib import Path from uuid import uuid4 from fastapi import UploadFile from sqlalchemy.orm import Session, joinedload from ..core.config import settings from ..core.exceptions import CodedHTTPException from ..core.time_utils import utc_now from ..models import ( Asset, Attachment, CalibrationRecord, Complaint, Contract, DemoEquipment, InsurancePolicy, User, Warranty, ) from ..services.audit import log_audit from ..services.permissions import Role ALLOWED_ENTITY_TYPES: set[str] = { "complaint", "contract", "calibration_record", "insurance", "demo_equipment", "asset", "warranty", } EXT_TO_MIME: dict[str, str] = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".pdf": "application/pdf", } ACCEPTED_CONTENT_TYPES: dict[str, set[str]] = { "image/jpeg": {"image/jpeg", "image/jpg", "image/pjpeg", "application/octet-stream", ""}, "image/png": {"image/png", "application/octet-stream", ""}, "application/pdf": {"application/pdf", "application/octet-stream", ""}, } COORDINATOR_UPLOAD_ENTITIES: set[str] = { "contract", "calibration_record", "insurance", "warranty", "demo_equipment", } def resolve_entity_department_id(db: Session, entity_type: str, entity_id: int) -> int: if entity_type not in ALLOWED_ENTITY_TYPES: raise CodedHTTPException( status_code=400, detail=f"Unsupported entity_type '{entity_type}'.", code="INVALID_ENTITY_TYPE", ) if entity_type == "asset": obj = db.query(Asset).filter(Asset.id == entity_id).first() if obj is None: raise CodedHTTPException(status_code=404, detail="Asset not found.", code="NOT_FOUND") return obj.department_id if entity_type == "complaint": obj = ( db.query(Complaint) .options(joinedload(Complaint.asset)) .filter(Complaint.id == entity_id) .first() ) if obj is None: raise CodedHTTPException(status_code=404, detail="Complaint not found.", code="NOT_FOUND") return obj.asset.department_id if entity_type == "demo_equipment": obj = db.query(DemoEquipment).filter(DemoEquipment.id == entity_id).first() if obj is None: raise CodedHTTPException(status_code=404, detail="Demo equipment not found.", code="NOT_FOUND") return obj.department_id if entity_type == "contract": obj = ( db.query(Contract) .options(joinedload(Contract.asset)) .filter(Contract.id == entity_id) .first() ) if obj is None: raise CodedHTTPException(status_code=404, detail="Contract not found.", code="NOT_FOUND") return obj.asset.department_id if entity_type == "warranty": obj = ( db.query(Warranty) .options(joinedload(Warranty.asset)) .filter(Warranty.id == entity_id) .first() ) if obj is None: raise CodedHTTPException(status_code=404, detail="Warranty not found.", code="NOT_FOUND") return obj.asset.department_id if entity_type == "insurance": obj = ( db.query(InsurancePolicy) .options(joinedload(InsurancePolicy.asset)) .filter(InsurancePolicy.id == entity_id) .first() ) if obj is None: raise CodedHTTPException(status_code=404, detail="Insurance policy not found.", code="NOT_FOUND") return obj.asset.department_id if entity_type == "calibration_record": obj = ( db.query(CalibrationRecord) .options(joinedload(CalibrationRecord.asset)) .filter(CalibrationRecord.id == entity_id) .first() ) if obj is None: raise CodedHTTPException(status_code=404, detail="Calibration record not found.", code="NOT_FOUND") return obj.asset.department_id raise CodedHTTPException(status_code=400, detail="Unsupported entity_type.", code="INVALID_ENTITY_TYPE") def assert_entity_visible(db: Session, user: User, entity_type: str, entity_id: int) -> int: dept_id = resolve_entity_department_id(db, entity_type, entity_id) if user.role == Role.department_user.value and dept_id != user.department_id: raise CodedHTTPException( status_code=403, detail="Access denied for another department's record.", code="FORBIDDEN", ) return dept_id def assert_can_upload(user: User, entity_type: str) -> None: if user.role in (Role.system_admin.value, Role.biomedical.value): return if user.role == Role.department_user.value: if entity_type != "complaint": raise CodedHTTPException( status_code=403, detail="Department users may only upload attachments to complaints.", code="FORBIDDEN", ) return if user.role == Role.coordinator.value: if entity_type not in COORDINATOR_UPLOAD_ENTITIES: raise CodedHTTPException( status_code=403, detail=f"Coordinators cannot upload attachments to '{entity_type}'.", code="FORBIDDEN", ) return raise CodedHTTPException( status_code=403, detail="You do not have permission to upload attachments.", code="FORBIDDEN", ) def assert_can_delete(user: User, att: Attachment) -> None: if user.role in (Role.system_admin.value, Role.biomedical.value): return if user.role != Role.management.value and att.uploaded_by_id == user.id: return raise CodedHTTPException( status_code=403, detail="You do not have permission to delete this attachment.", code="FORBIDDEN", ) def validate_and_read_upload(file: UploadFile) -> tuple[str, str, bytes]: original_name = Path(file.filename or "").name ext = Path(original_name).suffix.lower() if ext not in EXT_TO_MIME: raise CodedHTTPException( status_code=400, detail="Only JPG, JPEG, PNG, and PDF files are allowed.", code="INVALID_FILE_TYPE", ) expected_mime = EXT_TO_MIME[ext] claimed_type = (file.content_type or "").lower().strip() if claimed_type not in ACCEPTED_CONTENT_TYPES[expected_mime]: raise CodedHTTPException( status_code=400, detail=f"Invalid content type '{claimed_type}' for {ext} file.", code="INVALID_FILE_TYPE", ) max_bytes = settings.MAX_UPLOAD_SIZE_MB * 1024 * 1024 content = file.file.read(max_bytes + 1) if len(content) > max_bytes: raise CodedHTTPException( status_code=413, detail=f"File size exceeds the {settings.MAX_UPLOAD_SIZE_MB} MB limit.", code="FILE_TOO_LARGE", ) if len(content) == 0: raise CodedHTTPException( status_code=400, detail="Uploaded file is empty.", code="INVALID_FILE_TYPE", ) # Magic bytes verification if expected_mime == "image/jpeg" and not content.startswith(b"\xff\xd8\xff"): raise CodedHTTPException( status_code=400, detail="File contents do not match a valid JPEG image.", code="INVALID_FILE_TYPE", ) if expected_mime == "image/png" and not content.startswith(b"\x89PNG\r\n\x1a\n"): raise CodedHTTPException( status_code=400, detail="File contents do not match a valid PNG image.", code="INVALID_FILE_TYPE", ) if expected_mime == "application/pdf" and not content.startswith(b"%PDF-"): raise CodedHTTPException( status_code=400, detail="File contents do not match a valid PDF document.", code="INVALID_FILE_TYPE", ) return original_name, expected_mime, content def save_attachment( db: Session, user: User, entity_type: str, entity_id: int, file: UploadFile, ) -> Attachment: assert_entity_visible(db, user, entity_type, entity_id) assert_can_upload(user, entity_type) original_name, mime_type, content = validate_and_read_upload(file) ext = Path(original_name).suffix.lower() stored_name = f"{uuid4().hex}{ext}" upload_dir = Path(settings.UPLOAD_DIR) upload_dir.mkdir(parents=True, exist_ok=True) dest_path = upload_dir / stored_name dest_path.write_bytes(content) att = Attachment( entity_type=entity_type, entity_id=entity_id, original_name=original_name, stored_name=stored_name, mime_type=mime_type, size_bytes=len(content), uploaded_by_id=user.id, uploaded_at=utc_now(), ) db.add(att) db.flush() log_audit( db, entity_type="attachment", entity_id=att.id, action="upload", changes={"parent_type": entity_type, "parent_id": entity_id, "original_name": original_name}, user_id=user.id, ) db.commit() db.refresh(att) return att def delete_attachment(db: Session, user: User, attachment_id: int) -> None: att = db.query(Attachment).filter(Attachment.id == attachment_id).first() if att is None: raise CodedHTTPException(status_code=404, detail="Attachment not found.", code="NOT_FOUND") assert_entity_visible(db, user, att.entity_type, att.entity_id) assert_can_delete(user, att) file_path = Path(settings.UPLOAD_DIR) / att.stored_name if file_path.is_file(): file_path.unlink() log_audit( db, entity_type="attachment", entity_id=att.id, action="delete", changes={"parent_type": att.entity_type, "parent_id": att.entity_id, "original_name": att.original_name}, user_id=user.id, ) db.delete(att) db.commit()