import uuid from datetime import date from fastapi import APIRouter, Depends, Query, Request, Response, status from sqlalchemy.ext.asyncio import AsyncSession from app.auth.dependencies import client_ip, get_current_user, require_role from app.common.enums import DCRStatus, ReportType, Role from app.common.exceptions import ValidationError from app.database.session import get_db from app.pdf.service import PDFService from app.reports.schemas import ( ApproveRequest, ChemistCallCreate, DCRCreate, DCRListItem, DCRRead, DCRUpdate, DoctorCallCreate, MissedVisitSet, ReturnRequest, StatusCounts, ) from app.reports.serializers import to_list_item, to_read from app.reports.service import DCRService from app.users.models import User router = APIRouter(prefix="/dcr", tags=["reports"]) # ---------------------------------------------------------------- queries @router.get("", response_model=list[DCRListItem]) async def list_reports( status_filter: DCRStatus | None = Query(default=None, alias="status"), report_type: ReportType | None = Query(default=None, alias="type"), date_from: date | None = None, date_to: date | None = None, limit: int = Query(default=50, ge=1, le=200), offset: int = Query(default=0, ge=0), headquarters_id: uuid.UUID | None = None, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ) -> list[DCRListItem]: """S2 (MR) and S6 (manager queue). Scope is applied in the service, never here; `headquarters_id` only narrows a manager's list to one of their headquarters.""" reports = await DCRService(db).list_for( current_user, headquarters_id=headquarters_id, status=status_filter, report_type=report_type, date_from=date_from, date_to=date_to, limit=limit, offset=offset, ) return [to_list_item(r) for r in reports] @router.get("/counts", response_model=StatusCounts) async def status_counts( headquarters_id: uuid.UUID | None = None, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ) -> StatusCounts: """Header counts — the deliberate, cheap replacement for the cut dashboards.""" return StatusCounts(**await DCRService(db).counts_for(current_user, headquarters_id)) @router.get("/{dcr_id}", response_model=DCRRead) async def get_report( dcr_id: uuid.UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read(await DCRService(db).get_for_view(dcr_id, current_user)) @router.get("/{dcr_id}/pdf") async def download_pdf( dcr_id: uuid.UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ) -> Response: """SEC-7 — served through an authorised endpoint, never as a guessable static path.""" dcr = await DCRService(db).get_for_view(dcr_id, current_user) if dcr.status != DCRStatus.APPROVED: raise ValidationError( "Only a finally approved report can be downloaded", {"current_status": dcr.status.value}, ) # An approved report never changes, so it is rendered from its data each time: every download # uses the current form layout, even for reports approved before the layout changed. content = await PDFService(db).render_bytes(dcr) prefix = {ReportType.PLAN: "PLAN", ReportType.SELF: "DCR-SELF"}.get(dcr.report_type, "DCR") filename = f"{prefix}-{dcr.mr.employee_code}-{dcr.report_date.isoformat()}.pdf" return Response( content=content, media_type="application/pdf", headers={"Content-Disposition": f'attachment; filename="{filename}"'}, ) # --------------------------------------------------------------- commands @router.post("", response_model=DCRRead, status_code=status.HTTP_201_CREATED) async def create_report( payload: DCRCreate, request: Request, current_user: User = Depends(require_role(Role.MR, Role.AM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read(await DCRService(db).create(payload, current_user, client_ip(request))) @router.patch("/{dcr_id}", response_model=DCRRead) async def update_report( dcr_id: uuid.UUID, payload: DCRUpdate, request: Request, current_user: User = Depends(require_role(Role.MR, Role.AM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( await DCRService(db).update_details( dcr_id, payload.model_dump(exclude_unset=True), current_user, client_ip(request) ) ) @router.post("/{dcr_id}/calls/doctor", response_model=DCRRead, status_code=201) async def add_doctor_call( dcr_id: uuid.UUID, payload: DoctorCallCreate, request: Request, current_user: User = Depends(require_role(Role.MR, Role.AM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( await DCRService(db).add_doctor_call(dcr_id, payload, current_user, client_ip(request)) ) @router.post("/{dcr_id}/calls/chemist", response_model=DCRRead, status_code=201) async def add_chemist_call( dcr_id: uuid.UUID, payload: ChemistCallCreate, request: Request, current_user: User = Depends(require_role(Role.MR, Role.AM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( await DCRService(db).add_chemist_call(dcr_id, payload, current_user, client_ip(request)) ) @router.delete("/{dcr_id}/calls/{call_id}", response_model=DCRRead) async def delete_call( dcr_id: uuid.UUID, call_id: uuid.UUID, request: Request, current_user: User = Depends(require_role(Role.MR, Role.AM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( await DCRService(db).delete_call(dcr_id, call_id, current_user, client_ip(request)) ) @router.put("/{dcr_id}/missed", response_model=DCRRead) async def set_missed_reason( dcr_id: uuid.UUID, payload: MissedVisitSet, request: Request, current_user: User = Depends(require_role(Role.MR)), db: AsyncSession = Depends(get_db), ) -> DCRRead: """End-of-day report: why a doctor or chemist on the day plan was not visited.""" return to_read( await DCRService(db).set_missed_reason(dcr_id, payload, current_user, client_ip(request)) ) @router.delete("/{dcr_id}/missed/{missed_id}", response_model=DCRRead) async def clear_missed_reason( dcr_id: uuid.UUID, missed_id: uuid.UUID, request: Request, current_user: User = Depends(require_role(Role.MR)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( await DCRService(db).clear_missed_reason( dcr_id, missed_id, current_user, client_ip(request) ) ) # ------------------------------------------------------------- transitions @router.post("/{dcr_id}/submit", response_model=DCRRead) async def submit( dcr_id: uuid.UUID, request: Request, current_user: User = Depends(require_role(Role.MR, Role.AM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read(await DCRService(db).submit(dcr_id, current_user, client_ip(request))) @router.post("/{dcr_id}/return", response_model=DCRRead) async def return_report( dcr_id: uuid.UUID, payload: ReturnRequest, request: Request, current_user: User = Depends(require_role(Role.AM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( await DCRService(db).return_report( dcr_id, payload.reason, current_user, client_ip(request) ) ) @router.post("/{dcr_id}/approve", response_model=DCRRead) async def approve( dcr_id: uuid.UUID, payload: ApproveRequest, request: Request, current_user: User = Depends(require_role(Role.AM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: """Area Manager final approval (headquarters scope is enforced by the service).""" return to_read( await DCRService(db).approve(dcr_id, payload.comment, current_user, client_ip(request)) )