import uuid from datetime import date from sqlalchemy import func, select from sqlalchemy.orm import selectinload from app.common.enums import DCRStatus, ReportType from app.common.repository import BaseRepository from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, StockistCall class DCRRepository(BaseRepository[DailyCallReport]): model = DailyCallReport async def get_full(self, dcr_id: uuid.UUID) -> DailyCallReport | None: stmt = ( select(DailyCallReport) .where(DailyCallReport.id == dcr_id) .options( selectinload(DailyCallReport.doctor_calls).selectinload(DoctorCall.doctor), selectinload(DailyCallReport.chemist_calls).selectinload(ChemistCall.chemist), selectinload(DailyCallReport.stockist_calls).selectinload(StockistCall.stockist), selectinload(DailyCallReport.missed_visits), selectinload(DailyCallReport.mr), selectinload(DailyCallReport.headquarters), # The plan's visits are the checklist an end-of-day report is measured against. selectinload(DailyCallReport.plan) .selectinload(DailyCallReport.doctor_calls) .selectinload(DoctorCall.doctor), selectinload(DailyCallReport.plan) .selectinload(DailyCallReport.chemist_calls) .selectinload(ChemistCall.chemist), selectinload(DailyCallReport.plan) .selectinload(DailyCallReport.stockist_calls) .selectinload(StockistCall.stockist), selectinload(DailyCallReport.actual), ) # The session keeps objects after commit (expire_on_commit=False), so without this the # report comes back with the call lists it had *before* an add or remove. .execution_options(populate_existing=True) ) return (await self.db.execute(stmt)).scalar_one_or_none() async def get_for_date( self, mr_user_id: uuid.UUID, report_date: date, report_type: ReportType ) -> DailyCallReport | None: """V1 pre-check. The database unique constraint is the real guarantee.""" stmt = select(DailyCallReport).where( DailyCallReport.mr_user_id == mr_user_id, DailyCallReport.report_date == report_date, DailyCallReport.report_type == report_type, ) return (await self.db.execute(stmt)).scalar_one_or_none() def _scoped( self, *, mr_user_id: uuid.UUID | None, hq_ids: set[uuid.UUID] | None, status: DCRStatus | None, date_from: date | None, date_to: date | None, report_type: ReportType | None = None, ): stmt = select(DailyCallReport) if mr_user_id is not None: stmt = stmt.where(DailyCallReport.mr_user_id == mr_user_id) if hq_ids is not None: # An empty scope must match nothing, not everything. stmt = stmt.where(DailyCallReport.headquarters_id.in_(hq_ids or [None])) if status is not None: stmt = stmt.where(DailyCallReport.status == status) if report_type is not None: stmt = stmt.where(DailyCallReport.report_type == report_type) else: # Without a type, lists and counts cover the MR approval workflow; an Area # Manager's own SELF reports are asked for by type. stmt = stmt.where(DailyCallReport.report_type != ReportType.SELF) if date_from is not None: stmt = stmt.where(DailyCallReport.report_date >= date_from) if date_to is not None: stmt = stmt.where(DailyCallReport.report_date <= date_to) return stmt async def list_scoped( self, *, mr_user_id: uuid.UUID | None = None, hq_ids: set[uuid.UUID] | None = None, status: DCRStatus | None = None, date_from: date | None = None, date_to: date | None = None, report_type: ReportType | None = None, limit: int = 50, offset: int = 0, ) -> list[DailyCallReport]: stmt = ( self._scoped( mr_user_id=mr_user_id, hq_ids=hq_ids, status=status, date_from=date_from, date_to=date_to, report_type=report_type, ) .options( selectinload(DailyCallReport.doctor_calls), selectinload(DailyCallReport.chemist_calls), selectinload(DailyCallReport.mr), selectinload(DailyCallReport.headquarters), ) .order_by(DailyCallReport.created_at.desc(), DailyCallReport.report_date.desc()) .limit(limit) .offset(offset) ) return list((await self.db.execute(stmt)).scalars().all()) async def status_counts( self, *, mr_user_id: uuid.UUID | None = None, hq_ids: set[uuid.UUID] | None = None ) -> dict[str, int]: stmt = self._scoped( mr_user_id=mr_user_id, hq_ids=hq_ids, status=None, date_from=None, date_to=None ).with_only_columns(DailyCallReport.status, func.count()).group_by(DailyCallReport.status) rows = (await self.db.execute(stmt)).all() return {str(status): count for status, count in rows}