"""Daily Call Report business rules — validation rules V1-V12 all live here. Routers never contain rules; repositories never contain rules. This module is the single place a reviewer needs to read to understand what the system enforces. Plan / end-of-day rules (P1-P5): P1 A PLAN lists the visits the MR intends to make; it carries no outcomes, and its times are planned times, so they may be later than "now". P2 An ACTUAL (end-of-day) report can be created only once the PLAN for that date is APPROVED by the Area Business Manager; it is linked to that plan. P3 Every planned doctor/chemist/stockist must, before submit, either have a visit recorded on the end-of-day report or a short note saying why it was missed. P4 Recording a visit for a doctor/chemist drops any "missed" note for them. P5 Visits not on the plan may still be added to the end-of-day report. Area Business Manager's own report (S1-S3): S1 An Area Business Manager files one SELF report per date, for one headquarters they manage; it needs no plan. S2 Its visits may be to any active doctor, chemist or stockist of that headquarters. Stockists are not assigned to an MR: an MR (or SFE) may visit any active stockist of the headquarters they cover. S3 There is no approval: submitting it makes it final (APPROVED, locked, PDF stored). """ import uuid from datetime import date, timedelta from sqlalchemy import select from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from app.approvals.state_machine import assert_editable, assert_transition from app.audit.service import AuditService from app.auth.dependencies import active_hq_ids_for_am, assert_can_view_dcr, visible_hq_ids from app.chemists.models import Chemist, ChemistAssignment from app.common.enums import ( FIELD_ROLES, AuditAction, DCRStatus, EntityType, MasterApproval, ReportType, Role, WorkflowAction, FIELD_ROLES, ) from app.common.exceptions import ( ConflictError, ForbiddenError, NotFoundError, ValidationError, ) from app.common.utils import local_now, local_today, snapshot, utcnow from app.config.settings import settings from app.doctors.models import Doctor, DoctorAssignment from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit, StockistCall from app.reports.repository import DCRRepository from app.reports.schemas import ( ChemistCallCreate, DCRCreate, DoctorCallCreate, MissedVisitSet, StockistCallCreate, ) from app.stockists.models import Stockist from app.reports.serializers import planned_visits from app.users.models import User #: Audit fields — the columns worth recording on a state change. _AUDIT_FIELDS = [ "report_type", "status", "report_date", "mr_remarks", "stockist_visit", "order_value", "return_reason", "returned_by_role", "submitted_at", "approved_at", ] #: Who files (and alone may edit or submit) each type of report. _OWNER_ROLE = {ReportType.PLAN: FIELD_ROLES, ReportType.ACTUAL: FIELD_ROLES, ReportType.SELF: frozenset({Role.ABM})} _LABEL = { ReportType.PLAN: "Daily Call Report (Plan)", ReportType.ACTUAL: "Daily Call Report (Done)", ReportType.SELF: "Daily Call Report (Self)", } def _clean(value: str | None) -> str | None: """Trimmed text, with blank input stored as NULL.""" value = (value or "").strip() return value or None class DCRService: def __init__(self, db: AsyncSession) -> None: self.db = db self.repo = DCRRepository(db) self.audit = AuditService(db) # ------------------------------------------------------------------ # Validation helpers # ------------------------------------------------------------------ def _validate_report_date(self, report_date: date, report_type: ReportType) -> None: today = local_today() # V2 — no future reports, except a plan, which may be made PLAN_AHEAD_DAYS ahead. ahead = settings.PLAN_AHEAD_DAYS if report_type == ReportType.PLAN else 0 latest = today + timedelta(days=ahead) if report_date > latest: raise ValidationError( f"A plan can be made at most {ahead} days ahead" if ahead else "Report date cannot be in the future", {"report_date": report_date.isoformat(), "latest_allowed": latest.isoformat()}, ) # V3 / A10 / Q8 — back-dating window. earliest = today - timedelta(days=settings.BACKDATING_WINDOW_DAYS) if report_date < earliest: raise ValidationError( f"Report date is older than the {settings.BACKDATING_WINDOW_DAYS}-day " "back-dating window", {"report_date": report_date.isoformat(), "earliest_allowed": earliest.isoformat()}, ) def _check_submission_deadline(self, report_date: date) -> None: """A16 / Q9 — report for date D must be submitted by end of D + N days.""" deadline = report_date + timedelta(days=settings.SUBMISSION_DEADLINE_DAYS) if local_today() > deadline: raise ValidationError( "Submission deadline for this report date has passed", {"report_date": report_date.isoformat(), "deadline": deadline.isoformat()}, ) async def _allowed_doctor_ids(self, dcr: DailyCallReport) -> set[uuid.UUID]: """V6 — an MR's assigned doctors; for a SELF report, those of its headquarters (S2).""" if dcr.report_type != ReportType.SELF: return await self._assigned_doctor_ids(dcr.mr_user_id) stmt = select(Doctor.id).where( Doctor.headquarters_id == dcr.headquarters_id, Doctor.is_active.is_(True), Doctor.approval_status == MasterApproval.APPROVED, ) return set((await self.db.execute(stmt)).scalars().all()) async def _allowed_chemist_ids(self, dcr: DailyCallReport) -> set[uuid.UUID]: if dcr.report_type != ReportType.SELF: return await self._assigned_chemist_ids(dcr.mr_user_id) stmt = select(Chemist.id).where( Chemist.headquarters_id == dcr.headquarters_id, Chemist.is_active.is_(True), Chemist.approval_status == MasterApproval.APPROVED, ) return set((await self.db.execute(stmt)).scalars().all()) async def _allowed_stockist_ids(self, dcr: DailyCallReport) -> set[uuid.UUID]: """Active stockists of the report's headquarters (SELF), or of every headquarters the MR / SFE covers.""" hq_ids = ( {dcr.headquarters_id} if dcr.report_type == ReportType.SELF else dcr.mr.covered_headquarter_ids or {dcr.headquarters_id} ) stmt = select(Stockist.id).where( Stockist.headquarters_id.in_(hq_ids), Stockist.is_active.is_(True), Stockist.approval_status == MasterApproval.APPROVED, ) return set((await self.db.execute(stmt)).scalars().all()) async def _assigned_doctor_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]: # A doctor the MR added is visitable only once the Area Business Manager has approved it. stmt = ( select(DoctorAssignment.doctor_id) .join(Doctor, Doctor.id == DoctorAssignment.doctor_id) .where( DoctorAssignment.mr_user_id == mr_user_id, DoctorAssignment.effective_to.is_(None), Doctor.approval_status == MasterApproval.APPROVED, ) ) return set((await self.db.execute(stmt)).scalars().all()) async def _assigned_chemist_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]: stmt = ( select(ChemistAssignment.chemist_id) .join(Chemist, Chemist.id == ChemistAssignment.chemist_id) .where( ChemistAssignment.mr_user_id == mr_user_id, ChemistAssignment.effective_to.is_(None), Chemist.approval_status == MasterApproval.APPROVED, ) ) return set((await self.db.execute(stmt)).scalars().all()) async def _build_doctor_call( self, dcr: DailyCallReport, payload: DoctorCallCreate, assigned: set[uuid.UUID] ) -> DoctorCall: # V6 — only doctors currently assigned to this MR may be called. if payload.doctor_id not in assigned: raise ValidationError( "Doctor is not in this report's headquarters" if dcr.report_type == ReportType.SELF else "Doctor is not assigned to this MR", {"doctor_id": str(payload.doctor_id)}, ) doctor = await self.db.get(Doctor, payload.doctor_id) if doctor is None: raise NotFoundError("Doctor not found", {"doctor_id": str(payload.doctor_id)}) # P1 — a planned visit has not happened yet, so it has no outcome. is_plan = dcr.report_type == ReportType.PLAN if not is_plan and payload.call_outcome is None: raise ValidationError( "call_outcome is required for a visit on a Daily Call Report (Done)", {"doctor_id": str(doctor.id)}, ) # V7 — conversion status is meaningful only for core doctors. if payload.conversion_status is not None and not doctor.is_core_doctor: raise ValidationError( "conversion_status may only be set for a core doctor", {"doctor_id": str(doctor.id), "is_core_doctor": False}, ) return DoctorCall( dcr_id=dcr.id, doctor_id=payload.doctor_id, visit_time=payload.visit_time, call_outcome=None if is_plan else payload.call_outcome, conversion_status=None if is_plan else payload.conversion_status, product_promote=payload.product_promote, product_sample=payload.product_sample, gift=None if is_plan else payload.gift, remarks=payload.remarks, ) async def _build_chemist_call( self, dcr: DailyCallReport, payload: ChemistCallCreate, assigned: set[uuid.UUID] ) -> ChemistCall: if payload.chemist_id not in assigned: raise ValidationError( "Chemist is not in this report's headquarters" if dcr.report_type == ReportType.SELF else "Chemist is not assigned to this MR", {"chemist_id": str(payload.chemist_id)}, ) if await self.db.get(Chemist, payload.chemist_id) is None: raise NotFoundError("Chemist not found", {"chemist_id": str(payload.chemist_id)}) return ChemistCall( dcr_id=dcr.id, chemist_id=payload.chemist_id, visit_time=payload.visit_time, pob=_clean(payload.pob), remarks=payload.remarks, ) async def _build_stockist_call( self, dcr: DailyCallReport, payload: StockistCallCreate, allowed: set[uuid.UUID] ) -> StockistCall: if payload.stockist_id not in allowed: raise ValidationError( "Stockist is not in this report's headquarters" if dcr.report_type == ReportType.SELF else "Stockist is not in a headquarters you cover", {"stockist_id": str(payload.stockist_id)}, ) is_plan = dcr.report_type == ReportType.PLAN return StockistCall( dcr_id=dcr.id, stockist_id=payload.stockist_id, visit_time=payload.visit_time, pob=None if is_plan else _clean(payload.pob), remarks=payload.remarks, ) # ------------------------------------------------------------------ # Commands # ------------------------------------------------------------------ async def create( self, data: DCRCreate, actor: User, ip: str | None = None ) -> DailyCallReport: if data.report_type == ReportType.SELF: if actor.role != Role.ABM: raise ForbiddenError("Only an Area Business Manager files a Daily Call Report (Self)") headquarters_id = await self._self_report_hq(actor, data.headquarters_id) elif actor.role not in FIELD_ROLES: raise ForbiddenError("Only an MR files a Daily Call Report (Plan) or (Done)") elif actor.headquarters_id is None: raise ValidationError("Only an MR with a headquarters can create a report") else: headquarters_id = actor.headquarters_id # snapshot (A1) self._validate_report_date(data.report_date, data.report_type) # V1 pre-check for a friendly 409; the unique constraint below is the guarantee. if await self.repo.get_for_date(actor.id, data.report_date, data.report_type): raise ConflictError( f"A {_LABEL[data.report_type]} already exists for this date", { "report_date": data.report_date.isoformat(), "report_type": data.report_type.value, }, ) plan_id = None if data.report_type == ReportType.ACTUAL: plan_id = (await self._approved_plan(actor.id, data.report_date)).id dcr = DailyCallReport( id=uuid.uuid4(), mr_user_id=actor.id, headquarters_id=headquarters_id, report_date=data.report_date, report_type=data.report_type, plan_id=plan_id, status=DCRStatus.DRAFT, mr_remarks=data.mr_remarks, ) self.db.add(dcr) doctor_ids = await self._allowed_doctor_ids(dcr) chemist_ids = await self._allowed_chemist_ids(dcr) seen_doctors: set[uuid.UUID] = set() for payload in data.doctor_calls: if payload.doctor_id in seen_doctors: raise ConflictError( "Duplicate doctor call in the same report", {"doctor_id": str(payload.doctor_id)}, ) seen_doctors.add(payload.doctor_id) self.db.add(await self._build_doctor_call(dcr, payload, doctor_ids)) seen_chemists: set[uuid.UUID] = set() for payload in data.chemist_calls: if payload.chemist_id in seen_chemists: raise ConflictError( "Duplicate chemist call in the same report", {"chemist_id": str(payload.chemist_id)}, ) seen_chemists.add(payload.chemist_id) self.db.add(await self._build_chemist_call(dcr, payload, chemist_ids)) await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.CREATE, after=snapshot(dcr, _AUDIT_FIELDS), ip_address=ip, ) try: await self.db.commit() except IntegrityError as exc: await self.db.rollback() raise ConflictError( "A report of this type already exists for this MR and date", {"cause": "uq_dcr_mr_date_type"}, ) from exc return await self.repo.get_full(dcr.id) async def update_details( self, dcr_id: uuid.UUID, changes: dict[str, str | None], actor: User, ip: str | None = None ) -> DailyCallReport: """Change the report-level free text: MR remarks, stockist visit, order.""" dcr = await self._get_owned_editable(dcr_id, actor) before = snapshot(dcr, _AUDIT_FIELDS) for field in ("mr_remarks", "stockist_visit", "order_value"): if field in changes: setattr(dcr, field, _clean(changes[field])) await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.UPDATE, before=before, after=snapshot(dcr, _AUDIT_FIELDS), ip_address=ip, ) await self.db.commit() return await self.repo.get_full(dcr.id) async def add_doctor_call( self, dcr_id: uuid.UUID, payload: DoctorCallCreate, actor: User, ip: str | None = None ) -> DailyCallReport: dcr = await self._get_owned_editable(dcr_id, actor) assigned = await self._allowed_doctor_ids(dcr) call = await self._build_doctor_call(dcr, payload, assigned) self._validate_visit_time(dcr, payload.visit_time) self.db.add(call) # Flush the insert on its own so the unique-violation surfaces HERE, as a # clean 409, rather than escaping from the audit flush or the final commit. try: await self.db.flush() except IntegrityError as exc: await self.db.rollback() # V5 — the doctor is already on this report. raise ConflictError( "This doctor has already been called on this report", {"doctor_id": str(payload.doctor_id), "cause": "uq_call_dcr_doctor"}, ) from exc await self._drop_missed_note(dcr, doctor_id=payload.doctor_id) await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.UPDATE, after={"added_doctor_call": str(payload.doctor_id)}, ip_address=ip, ) await self.db.commit() return await self.repo.get_full(dcr.id) async def add_chemist_call( self, dcr_id: uuid.UUID, payload: ChemistCallCreate, actor: User, ip: str | None = None ) -> DailyCallReport: dcr = await self._get_owned_editable(dcr_id, actor) assigned = await self._allowed_chemist_ids(dcr) call = await self._build_chemist_call(dcr, payload, assigned) self._validate_visit_time(dcr, payload.visit_time) self.db.add(call) try: await self.db.flush() except IntegrityError as exc: await self.db.rollback() raise ConflictError( "This chemist has already been called on this report", {"chemist_id": str(payload.chemist_id), "cause": "uq_call_dcr_chemist"}, ) from exc await self._drop_missed_note(dcr, chemist_id=payload.chemist_id) await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.UPDATE, after={"added_chemist_call": str(payload.chemist_id)}, ip_address=ip, ) await self.db.commit() return await self.repo.get_full(dcr.id) async def add_stockist_call( self, dcr_id: uuid.UUID, payload: StockistCallCreate, actor: User, ip: str | None = None ) -> DailyCallReport: dcr = await self._get_owned_editable(dcr_id, actor) allowed = await self._allowed_stockist_ids(dcr) call = await self._build_stockist_call(dcr, payload, allowed) self._validate_visit_time(dcr, payload.visit_time) self.db.add(call) try: await self.db.flush() except IntegrityError as exc: await self.db.rollback() raise ConflictError( "This stockist has already been called on this report", {"stockist_id": str(payload.stockist_id), "cause": "uq_call_dcr_stockist"}, ) from exc await self._drop_missed_note(dcr, stockist_id=payload.stockist_id) await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.UPDATE, after={"added_stockist_call": str(payload.stockist_id)}, ip_address=ip, ) await self.db.commit() return await self.repo.get_full(dcr.id) def _validate_visit_time(self, dcr: DailyCallReport, visit_time) -> None: """V11 — a visit time on today's report cannot be in the future (P1: plans excepted).""" if dcr.report_type != ReportType.PLAN and dcr.report_date == local_today(): # Visit times are entered in the company's local time (APP_TIMEZONE), so they # must be compared with local "now" — not the server's UTC clock. if visit_time > local_now().time() and settings.ENVIRONMENT == "production": raise ValidationError( "Visit time cannot be in the future", {"visit_time": str(visit_time)} ) async def delete_call( self, dcr_id: uuid.UUID, call_id: uuid.UUID, actor: User, ip: str | None = None ) -> DailyCallReport: dcr = await self._get_owned_editable(dcr_id, actor) call = ( await self.db.get(DoctorCall, call_id) or await self.db.get(ChemistCall, call_id) or await self.db.get(StockistCall, call_id) ) if call is None or call.dcr_id != dcr.id: raise NotFoundError("Call not found on this report", {"call_id": str(call_id)}) await self.db.delete(call) await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.DELETE, before={"removed_call": str(call_id)}, ip_address=ip, ) await self.db.commit() return await self.repo.get_full(dcr.id) async def set_missed_reason( self, dcr_id: uuid.UUID, payload: MissedVisitSet, actor: User, ip: str | None = None ) -> DailyCallReport: """P3 — record (or reword) why a planned doctor/chemist/stockist was not visited.""" dcr = await self._get_owned_editable(dcr_id, actor) if dcr.report_type != ReportType.ACTUAL or dcr.plan is None: raise ValidationError("Missed-visit notes belong on a Daily Call Report (Done)") targets = [t for t in (payload.doctor_id, payload.chemist_id, payload.stockist_id) if t] if len(targets) != 1: raise ValidationError("Give exactly one of doctor_id, chemist_id or stockist_id") reason = _clean(payload.reason) if reason is None: raise ValidationError("Say briefly why the visit was missed") target_id = targets[0] line = next((p for p in planned_visits(dcr) if p.target_id == target_id), None) if line is None: raise ValidationError( "This doctor, chemist or stockist is not on the plan", {"target_id": str(target_id)} ) if line.status == "VISITED": raise ConflictError( "A visit is already recorded for this doctor, chemist or stockist; remove it first", {"target_id": str(target_id)}, ) note = next( ( m for m in dcr.missed_visits if (m.doctor_id or m.chemist_id or m.stockist_id) == target_id ), None, ) before = {"reason": note.reason} if note else None if note is None: self.db.add( MissedVisit( dcr_id=dcr.id, doctor_id=payload.doctor_id, chemist_id=payload.chemist_id, stockist_id=payload.stockist_id, reason=reason, ) ) else: note.reason = reason await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.UPDATE, before=before, after={"missed_visit": str(target_id), "reason": reason}, ip_address=ip, ) await self.db.commit() return await self.repo.get_full(dcr.id) async def clear_missed_reason( self, dcr_id: uuid.UUID, missed_id: uuid.UUID, actor: User, ip: str | None = None ) -> DailyCallReport: dcr = await self._get_owned_editable(dcr_id, actor) note = next((m for m in dcr.missed_visits if m.id == missed_id), None) if note is None: raise NotFoundError( "Missed-visit note not found on this report", {"id": str(missed_id)} ) await self.db.delete(note) await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.DELETE, before={ "missed_visit": str(note.doctor_id or note.chemist_id or note.stockist_id), "reason": note.reason, }, ip_address=ip, ) await self.db.commit() return await self.repo.get_full(dcr.id) # ------------------------------------------------------------------ # Workflow transitions # ------------------------------------------------------------------ async def submit( self, dcr_id: uuid.UUID, actor: User, ip: str | None = None ) -> DailyCallReport: dcr = await self.repo.get_full(dcr_id) if dcr is None: raise NotFoundError("Report not found", {"id": str(dcr_id)}) await assert_can_view_dcr(self.db, actor, dcr) if dcr.mr_user_id != actor.id or actor.role not in _OWNER_ROLE[dcr.report_type]: raise ForbiddenError("Only the report's owner can submit it") if dcr.report_type == ReportType.SELF: return await self._finalise_self_report(dcr, actor, ip) if dcr.status == DCRStatus.PENDING_ABM: return dcr # already submitted (a double click): nothing more to do transition = assert_transition(dcr.status, WorkflowAction.SUBMIT, actor.role) self._check_submit_contents(dcr) self._check_submission_deadline(dcr.report_date) before = snapshot(dcr, _AUDIT_FIELDS) dcr.status = transition.to_status dcr.submitted_at = utcnow() dcr.return_reason = None dcr.returned_by_role = None dcr.current_am_user_id = await self._current_am_for_hq(dcr.headquarters_id) await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.SUBMIT, before=before, after=snapshot(dcr, _AUDIT_FIELDS), ip_address=ip, ) await self.db.commit() return await self.repo.get_full(dcr.id) async def _finalise_self_report( self, dcr: DailyCallReport, actor: User, ip: str | None ) -> DailyCallReport: """S3 — an Area Business Manager's own report is final once submitted; nobody approves it.""" if dcr.status == DCRStatus.APPROVED: return dcr # already submitted (a double click) assert_editable(dcr.status) self._check_submit_contents(dcr) self._check_submission_deadline(dcr.report_date) before = snapshot(dcr, _AUDIT_FIELDS) dcr.status = DCRStatus.APPROVED dcr.submitted_at = dcr.approved_at = utcnow() await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.SUBMIT, before=before, after=snapshot(dcr, _AUDIT_FIELDS), ip_address=ip, ) from app.pdf.service import PDFService full = await self.repo.get_full(dcr.id) dcr.pdf_path = await PDFService(self.db).render_and_store(full, approver=actor) await self.db.commit() return await self.repo.get_full(dcr.id) async def return_report( self, dcr_id: uuid.UUID, reason: str, actor: User, ip: str | None = None ) -> DailyCallReport: dcr = await self._get_in_scope(dcr_id, actor) transition = assert_transition(dcr.status, WorkflowAction.RETURN, actor.role) before = snapshot(dcr, _AUDIT_FIELDS) dcr.status = transition.to_status dcr.return_reason = reason dcr.returned_by_role = actor.role # data, not a separate status await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.RETURN, before=before, after=snapshot(dcr, _AUDIT_FIELDS), comment=reason, ip_address=ip, ) await self.db.commit() return await self.repo.get_full(dcr.id) async def approve( self, dcr_id: uuid.UUID, comment: str | None, actor: User, ip: str | None = None ) -> DailyCallReport: """Area Business Manager final approval. APPROVED is terminal and immutable.""" dcr = await self._get_in_scope(dcr_id, actor) if dcr.status == DCRStatus.APPROVED and actor.role == Role.ABM: return dcr # already approved (a double click): the report stays as it is transition = assert_transition(dcr.status, WorkflowAction.APPROVE, actor.role) before = snapshot(dcr, _AUDIT_FIELDS) dcr.status = transition.to_status dcr.approved_at = utcnow() await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.APPROVE, before=before, after=snapshot(dcr, _AUDIT_FIELDS), comment=comment, ip_address=ip, ) # PDF is generated synchronously — it takes about a second, and adding a task # queue for one one-second job is infrastructure you must then operate. from app.pdf.service import PDFService full = await self.repo.get_full(dcr.id) dcr.pdf_path = await PDFService(self.db).render_and_store(full, approver=actor) await self.db.commit() return await self.repo.get_full(dcr.id) # ------------------------------------------------------------------ # Queries # ------------------------------------------------------------------ async def get_for_view(self, dcr_id: uuid.UUID, actor: User) -> DailyCallReport: dcr = await self.repo.get_full(dcr_id) if dcr is None: raise NotFoundError("Report not found", {"id": str(dcr_id)}) await assert_can_view_dcr(self.db, actor, dcr) return dcr async def _hq_scope( self, actor: User, headquarters_id: uuid.UUID | None ) -> set[uuid.UUID] | None: """The headquarters a manager's lists cover: all they may see, or the one they chose — narrowed, never widened (one outside their scope gives nothing).""" allowed = await visible_hq_ids(self.db, actor) if headquarters_id is None: return allowed return {headquarters_id} if allowed is None or headquarters_id in allowed else set() async def list_for( self, actor: User, headquarters_id: uuid.UUID | None = None, **filters ) -> list[DailyCallReport]: # An Area Business Manager's SELF list is their own reports, not their headquarters'. if actor.role in FIELD_ROLES or ( actor.role == Role.ABM and filters.get("report_type") == ReportType.SELF ): return await self.repo.list_scoped(mr_user_id=actor.id, **filters) hq_ids = await self._hq_scope(actor, headquarters_id) return await self.repo.list_scoped(hq_ids=hq_ids, **filters) async def counts_for( self, actor: User, headquarters_id: uuid.UUID | None = None ) -> dict[str, int]: if actor.role in FIELD_ROLES: return await self.repo.status_counts(mr_user_id=actor.id) return await self.repo.status_counts(hq_ids=await self._hq_scope(actor, headquarters_id)) # ------------------------------------------------------------------ # Internals # ------------------------------------------------------------------ async def _get_owned_editable(self, dcr_id: uuid.UUID, actor: User) -> DailyCallReport: """Owner + editable-status guard for every data-changing operation (V9/V10).""" dcr = await self.repo.get_full(dcr_id) if dcr is None: raise NotFoundError("Report not found", {"id": str(dcr_id)}) await assert_can_view_dcr(self.db, actor, dcr) if dcr.mr_user_id != actor.id or actor.role not in _OWNER_ROLE[dcr.report_type]: raise ForbiddenError("Only the report's owner can modify report data") assert_editable(dcr.status) return dcr async def _self_report_hq(self, actor: User, headquarters_id: uuid.UUID | None) -> uuid.UUID: """S1 — one of the headquarters this Area Business Manager manages; implied when there is one.""" managed = await active_hq_ids_for_am(self.db, actor.id) if headquarters_id is None and len(managed) == 1: return next(iter(managed)) if headquarters_id is None: raise ValidationError("Choose the headquarters this report is for") if headquarters_id not in managed: raise ForbiddenError("You do not manage this headquarters") return headquarters_id async def _get_in_scope(self, dcr_id: uuid.UUID, actor: User) -> DailyCallReport: dcr = await self.repo.get_full(dcr_id) if dcr is None: raise NotFoundError("Report not found", {"id": str(dcr_id)}) await assert_can_view_dcr(self.db, actor, dcr) return dcr def _check_submit_contents(self, dcr: DailyCallReport) -> None: if dcr.report_type == ReportType.PLAN: if not dcr.doctor_calls and not dcr.chemist_calls and not dcr.stockist_calls: raise ValidationError("Plan at least one doctor, chemist or stockist visit to submit") return # P3 — every planned visit is either recorded or explained. pending = [p for p in planned_visits(dcr) if p.status == "PENDING"] if pending: raise ValidationError( "Record a visit or add a missed-visit note for every planned doctor, chemist and stockist", {"pending": [p.name for p in pending]}, ) # V4 — at least one doctor call, unless the planned visits were all explained. if not dcr.doctor_calls and not dcr.missed_visits: raise ValidationError("A report must contain at least one doctor call to submit") async def _approved_plan(self, mr_user_id: uuid.UUID, report_date: date) -> DailyCallReport: """P2 — the end-of-day report follows an Area-Manager-approved plan.""" plan = await self.repo.get_for_date(mr_user_id, report_date, ReportType.PLAN) if plan is None: raise ValidationError( "Create your Daily Call Report (Plan) for this date first; " "the Done report follows it", {"report_date": report_date.isoformat()}, ) if plan.status != DCRStatus.APPROVED: raise ValidationError( "Your Daily Call Report (Plan) for this date must be approved " "by the Area Business Manager first", {"report_date": report_date.isoformat(), "plan_status": plan.status.value}, ) return plan async def _drop_missed_note( self, dcr: DailyCallReport, doctor_id: uuid.UUID | None = None, chemist_id: uuid.UUID | None = None, stockist_id: uuid.UUID | None = None, ) -> None: """P4 — a recorded visit replaces any note saying it was missed.""" for note in dcr.missed_visits: if ( (doctor_id and note.doctor_id == doctor_id) or (chemist_id and note.chemist_id == chemist_id) or (stockist_id and note.stockist_id == stockist_id) ): await self.db.delete(note) async def _current_am_for_hq(self, headquarters_id: uuid.UUID) -> uuid.UUID | None: from app.organization.models import AMHeadquarters # Recorded only; any Area Business Manager of the headquarters may act on the report. stmt = ( select(AMHeadquarters.area_manager_user_id) .where( AMHeadquarters.headquarters_id == headquarters_id, AMHeadquarters.effective_to.is_(None), ) .order_by(AMHeadquarters.effective_from, AMHeadquarters.created_at) ) return (await self.db.execute(stmt)).scalars().first()