This commit is contained in:
Shubhankar45
2026-10-27 12:03:31 +00:00
parent 2ed3945b5d
commit 4e5e95775d
104 changed files with 5210 additions and 606 deletions
+82 -11
View File
@@ -1,4 +1,12 @@
"""The Daily Call Report and its call rows — the core artefact of the MVP."""
"""The Daily Call Report and its call rows — the core artefact of the MVP.
Each working day an MR files two reports (see ``ReportType``): a morning PLAN of the
doctors and chemists they intend to visit, and an end-of-day ACTUAL report of the visits
that happened. Both share this table and its call rows; the ACTUAL report points at its
plan, and records why any planned visit was missed in ``missed_visit``.
An Area Manager files a SELF report of their own visits in the same table; ``mr_user_id``
is then the Area Manager (the report's owner), and submitting it makes it final."""
import uuid
from datetime import date, datetime, time
@@ -14,19 +22,24 @@ from sqlalchemy import (
Time,
UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, Role
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, ReportType, Role
from app.database.base import Base, TimestampMixin, UUIDMixin
class DailyCallReport(Base, UUIDMixin, TimestampMixin):
__tablename__ = "daily_call_report"
__table_args__ = (
# V1 / A9 — ONE report per MR per calendar date. Enforced in the database and
# not only in the service, so a double-submit race cannot create two reports.
UniqueConstraint("mr_user_id", "report_date", name="uq_dcr_mr_date"),
# V1 / A9 — ONE report of each type per MR per calendar date. Enforced in the
# database and not only in the service, so a double-submit race cannot create two.
UniqueConstraint("mr_user_id", "report_date", "report_type", name="uq_dcr_mr_date_type"),
# A plan is followed by at most one end-of-day report.
UniqueConstraint("plan_id", name="uq_dcr_plan_id"),
# Only an end-of-day report points at a plan.
CheckConstraint("report_type = 'ACTUAL' OR plan_id IS NULL", name="ck_dcr_plan_link"),
# An approved report must carry its approval timestamp, and nothing else may.
CheckConstraint(
"(status = 'APPROVED' AND approved_at IS NOT NULL) "
@@ -44,6 +57,16 @@ class DailyCallReport(Base, UUIDMixin, TimestampMixin):
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False
)
report_date: Mapped[date] = mapped_column(Date, nullable=False)
report_type: Mapped[ReportType] = mapped_column(
Enum(ReportType, name="report_type_enum", native_enum=False, length=10),
default=ReportType.ACTUAL,
nullable=False,
)
#: The approved morning plan an end-of-day report is filed against. NULL for plans,
#: and for end-of-day reports filed before plans existed.
plan_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("daily_call_report.id", ondelete="RESTRICT")
)
status: Mapped[DCRStatus] = mapped_column(
Enum(DCRStatus, name="dcr_status_enum", native_enum=False, length=20),
default=DCRStatus.DRAFT,
@@ -81,6 +104,16 @@ class DailyCallReport(Base, UUIDMixin, TimestampMixin):
chemist_calls: Mapped[list["ChemistCall"]] = relationship(
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
)
missed_visits: Mapped[list["MissedVisit"]] = relationship(
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
)
#: Loaded explicitly by the repository (self-referential, so never eagerly by default).
plan: Mapped["DailyCallReport | None"] = relationship(
remote_side="DailyCallReport.id", foreign_keys=[plan_id], back_populates="actual"
)
actual: Mapped["DailyCallReport | None"] = relationship(
foreign_keys=[plan_id], back_populates="plan", uselist=False
)
@property
def is_locked(self) -> bool:
@@ -103,18 +136,25 @@ class DoctorCall(Base, UUIDMixin, TimestampMixin):
doctor_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("doctor.id", ondelete="RESTRICT"), nullable=False
)
#: On a plan this is the planned time; on an end-of-day report, when the visit happened.
visit_time: Mapped[time] = mapped_column(Time, nullable=False)
call_outcome: Mapped[CallOutcome] = mapped_column(
Enum(CallOutcome, name="call_outcome_enum", native_enum=False, length=20),
nullable=False,
#: Required on an end-of-day report; a planned visit has no outcome yet (NULL).
call_outcome: Mapped[CallOutcome | None] = mapped_column(
Enum(CallOutcome, name="call_outcome_enum", native_enum=False, length=20)
)
#: V7 — only permitted when the doctor is a core doctor.
conversion_status: Mapped[ConversionStatus | None] = mapped_column(
Enum(ConversionStatus, name="conversion_status_enum", native_enum=False, length=20)
)
#: The printed form's "PRODUCT PROMOTE" and "PRODUCT SAMPLE" columns.
product_promote: Mapped[str | None] = mapped_column(String(200))
product_sample: Mapped[str | None] = mapped_column(String(200))
#: The printed form's "PRODUCT PROMOTE" and "PRODUCT SAMPLE" columns; several per visit.
product_promote: Mapped[list[str]] = mapped_column(
ARRAY(String(200)), default=list, server_default="{}", nullable=False
)
product_sample: Mapped[list[str]] = mapped_column(
ARRAY(String(200)), default=list, server_default="{}", nullable=False
)
#: A gift given to the doctor on this visit, typed in by the MR.
gift: Mapped[str | None] = mapped_column(String(200))
remarks: Mapped[str | None] = mapped_column(Text)
dcr: Mapped["DailyCallReport"] = relationship(back_populates="doctor_calls")
@@ -142,3 +182,34 @@ class ChemistCall(Base, UUIDMixin, TimestampMixin):
dcr: Mapped["DailyCallReport"] = relationship(back_populates="chemist_calls")
chemist: Mapped["Chemist"] = relationship(lazy="selectin") # noqa: F821
class MissedVisit(Base, UUIDMixin, TimestampMixin):
"""Why a doctor or chemist on the approved plan was not visited that day.
Belongs to the end-of-day report; exactly one of doctor/chemist is set.
"""
__tablename__ = "missed_visit"
__table_args__ = (
UniqueConstraint("dcr_id", "doctor_id", name="uq_missed_dcr_doctor"),
UniqueConstraint("dcr_id", "chemist_id", name="uq_missed_dcr_chemist"),
CheckConstraint(
"(doctor_id IS NULL) <> (chemist_id IS NULL)", name="ck_missed_one_target"
),
)
dcr_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey("daily_call_report.id", ondelete="CASCADE"),
nullable=False,
)
doctor_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("doctor.id", ondelete="RESTRICT")
)
chemist_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("chemist.id", ondelete="RESTRICT")
)
reason: Mapped[str] = mapped_column(Text, nullable=False)
dcr: Mapped["DailyCallReport"] = relationship(back_populates="missed_visits")
+21 -3
View File
@@ -4,7 +4,7 @@ from datetime import date
from sqlalchemy import func, select
from sqlalchemy.orm import selectinload
from app.common.enums import DCRStatus
from app.common.enums import DCRStatus, ReportType
from app.common.repository import BaseRepository
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall
@@ -19,8 +19,17 @@ class DCRRepository(BaseRepository[DailyCallReport]):
.options(
selectinload(DailyCallReport.doctor_calls).selectinload(DoctorCall.doctor),
selectinload(DailyCallReport.chemist_calls).selectinload(ChemistCall.chemist),
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.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.
@@ -29,12 +38,13 @@ class DCRRepository(BaseRepository[DailyCallReport]):
return (await self.db.execute(stmt)).scalar_one_or_none()
async def get_for_date(
self, mr_user_id: uuid.UUID, report_date: 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()
@@ -46,6 +56,7 @@ class DCRRepository(BaseRepository[DailyCallReport]):
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:
@@ -55,6 +66,12 @@ class DCRRepository(BaseRepository[DailyCallReport]):
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:
@@ -69,13 +86,14 @@ class DCRRepository(BaseRepository[DailyCallReport]):
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,
date_from=date_from, date_to=date_to, report_type=report_type,
)
.options(
selectinload(DailyCallReport.doctor_calls),
+49 -11
View File
@@ -5,7 +5,7 @@ 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, 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
@@ -17,6 +17,7 @@ from app.reports.schemas import (
DCRRead,
DCRUpdate,
DoctorCallCreate,
MissedVisitSet,
ReturnRequest,
StatusCounts,
)
@@ -33,17 +34,22 @@ router = APIRouter(prefix="/dcr", tags=["reports"])
@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."""
"""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,
@@ -54,10 +60,12 @@ async def list_reports(
@router.get("/counts", response_model=StatusCounts)
async def status_counts(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
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))
return StatusCounts(**await DCRService(db).counts_for(current_user, headquarters_id))
@router.get("/{dcr_id}", response_model=DCRRead)
@@ -87,7 +95,8 @@ async def download_pdf(
# uses the current form layout, even for reports approved before the layout changed.
content = await PDFService(db).render_bytes(dcr)
filename = f"DCR-{dcr.mr.employee_code}-{dcr.report_date.isoformat()}.pdf"
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",
@@ -102,7 +111,7 @@ async def download_pdf(
async def create_report(
payload: DCRCreate,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
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)))
@@ -113,7 +122,7 @@ async def update_report(
dcr_id: uuid.UUID,
payload: DCRUpdate,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
current_user: User = Depends(require_role(Role.MR, Role.AM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
@@ -128,7 +137,7 @@ async def add_doctor_call(
dcr_id: uuid.UUID,
payload: DoctorCallCreate,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
current_user: User = Depends(require_role(Role.MR, Role.AM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
@@ -141,7 +150,7 @@ async def add_chemist_call(
dcr_id: uuid.UUID,
payload: ChemistCallCreate,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
current_user: User = Depends(require_role(Role.MR, Role.AM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
@@ -154,7 +163,7 @@ async def delete_call(
dcr_id: uuid.UUID,
call_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
current_user: User = Depends(require_role(Role.MR, Role.AM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
@@ -162,6 +171,35 @@ async def delete_call(
)
@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
@@ -169,7 +207,7 @@ async def delete_call(
async def submit(
dcr_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
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)))
+71 -8
View File
@@ -1,22 +1,49 @@
import uuid
from datetime import date, datetime, time
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from pydantic import BaseModel, ConfigDict, Field, field_validator
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, Role
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, ReportType, Role
from app.config.settings import settings
#: How many promoted (or sample) products one doctor visit may name.
MAX_PRODUCTS_PER_VISIT = 10
def _product_list(value: str | list[str] | None) -> list[str]:
"""Trimmed, de-duplicated product names. A single string is still accepted."""
items = [value] if isinstance(value, str) else value or []
names: list[str] = []
for item in items:
if not isinstance(item, str):
raise ValueError("Product names must be text")
name = item.strip()
if len(name) > 200:
raise ValueError("A product name must be 200 characters or fewer")
if name and name.casefold() not in {n.casefold() for n in names}:
names.append(name)
if len(names) > MAX_PRODUCTS_PER_VISIT:
raise ValueError(f"Choose at most {MAX_PRODUCTS_PER_VISIT} products")
return names
class DoctorCallCreate(BaseModel):
doctor_id: uuid.UUID
visit_time: time
call_outcome: CallOutcome
#: Required on an end-of-day report; ignored on a plan (a planned visit has no outcome).
call_outcome: CallOutcome | None = None
#: V7 — accepted only when the doctor is flagged as a core doctor.
conversion_status: ConversionStatus | None = None
product_promote: str | None = Field(default=None, max_length=200)
product_sample: str | None = Field(default=None, max_length=200)
product_promote: list[str] = Field(default_factory=list)
product_sample: list[str] = Field(default_factory=list)
gift: str | None = Field(default=None, max_length=200)
remarks: str | None = Field(default=None, max_length=2000)
_products = field_validator("product_promote", "product_sample", mode="before")(
_product_list
)
class ChemistCallCreate(BaseModel):
chemist_id: uuid.UUID
@@ -34,10 +61,11 @@ class DoctorCallRead(BaseModel):
doctor_speciality: str | None
is_core_doctor: bool
visit_time: time
call_outcome: CallOutcome
call_outcome: CallOutcome | None
conversion_status: ConversionStatus | None
product_promote: str | None
product_sample: str | None
product_promote: list[str]
product_sample: list[str]
gift: str | None = None
remarks: str | None
@@ -54,6 +82,9 @@ class ChemistCallRead(BaseModel):
class DCRCreate(BaseModel):
report_date: date
report_type: ReportType = ReportType.ACTUAL
#: SELF reports only: which of the Area Manager's headquarters the visits were in.
headquarters_id: uuid.UUID | None = None
mr_remarks: str | None = Field(default=None, max_length=2000)
doctor_calls: list[DoctorCallCreate] = Field(default_factory=list)
chemist_calls: list[ChemistCallCreate] = Field(default_factory=list)
@@ -65,6 +96,31 @@ class DCRUpdate(BaseModel):
order_value: str | None = Field(default=None, max_length=100)
class MissedVisitSet(BaseModel):
"""Why one planned doctor OR chemist was not visited (end-of-day report only)."""
doctor_id: uuid.UUID | None = None
chemist_id: uuid.UUID | None = None
reason: str = Field(min_length=3, max_length=500)
class PlannedVisitRead(BaseModel):
"""One line of the approved plan, checked against the end-of-day report.
VISITED — the MR recorded a visit; MISSED — the MR explained why not;
PENDING — neither yet (the report cannot be submitted while any remain).
"""
kind: Literal["DOCTOR", "CHEMIST"]
target_id: uuid.UUID
name: str
is_core_doctor: bool
planned_time: time
status: Literal["VISITED", "MISSED", "PENDING"]
missed_visit_id: uuid.UUID | None
missed_reason: str | None
class ReturnRequest(BaseModel):
"""V8 — a manager must say WHY. This reason is what makes the audit trail useful."""
@@ -82,6 +138,7 @@ class DCRListItem(BaseModel):
id: uuid.UUID
report_date: date
report_type: ReportType
status: DCRStatus
mr_user_id: uuid.UUID
mr_name: str
@@ -104,8 +161,12 @@ class DCRRead(BaseModel):
headquarters_id: uuid.UUID
headquarters_name: str
report_date: date
report_type: ReportType
status: DCRStatus
is_locked: bool
#: End-of-day report → its plan; plan → its end-of-day report, once started.
plan_id: uuid.UUID | None
actual_report_id: uuid.UUID | None
mr_remarks: str | None
stockist_visit: str | None
order_value: str | None
@@ -115,6 +176,8 @@ class DCRRead(BaseModel):
approved_at: datetime | None
doctor_calls: list[DoctorCallRead]
chemist_calls: list[ChemistCallRead]
#: End-of-day report only: the approved plan, line by line, with what became of it.
planned_visits: list[PlannedVisitRead]
class StatusCounts(BaseModel):
+39
View File
@@ -6,9 +6,42 @@ from app.reports.schemas import (
DCRListItem,
DCRRead,
DoctorCallRead,
PlannedVisitRead,
)
def planned_visits(dcr: DailyCallReport) -> list[PlannedVisitRead]:
"""The approved plan, line by line, checked against this end-of-day report."""
plan = dcr.plan
if plan is None:
return []
visited = {c.doctor_id for c in dcr.doctor_calls} | {c.chemist_id for c in dcr.chemist_calls}
missed = {m.doctor_id or m.chemist_id: m for m in dcr.missed_visits}
def line(kind, target_id, name, is_core, planned_time) -> PlannedVisitRead:
note = missed.get(target_id)
status = "VISITED" if target_id in visited else "MISSED" if note else "PENDING"
return PlannedVisitRead(
kind=kind,
target_id=target_id,
name=name,
is_core_doctor=is_core,
planned_time=planned_time,
status=status,
missed_visit_id=note.id if note and status == "MISSED" else None,
missed_reason=note.reason if note and status == "MISSED" else None,
)
lines = [
line("DOCTOR", c.doctor_id, c.doctor.name, c.doctor.is_core_doctor, c.visit_time)
for c in plan.doctor_calls
] + [
line("CHEMIST", c.chemist_id, c.chemist.name, False, c.visit_time)
for c in plan.chemist_calls
]
return sorted(lines, key=lambda x: x.planned_time)
def to_read(dcr: DailyCallReport) -> DCRRead:
return DCRRead(
id=dcr.id,
@@ -18,8 +51,11 @@ def to_read(dcr: DailyCallReport) -> DCRRead:
headquarters_id=dcr.headquarters_id,
headquarters_name=dcr.headquarters.name,
report_date=dcr.report_date,
report_type=dcr.report_type,
status=dcr.status,
is_locked=dcr.is_locked,
plan_id=dcr.plan_id,
actual_report_id=dcr.actual.id if dcr.actual else None,
mr_remarks=dcr.mr_remarks,
stockist_visit=dcr.stockist_visit,
order_value=dcr.order_value,
@@ -39,6 +75,7 @@ def to_read(dcr: DailyCallReport) -> DCRRead:
conversion_status=c.conversion_status,
product_promote=c.product_promote,
product_sample=c.product_sample,
gift=c.gift,
remarks=c.remarks,
)
for c in sorted(dcr.doctor_calls, key=lambda x: x.visit_time)
@@ -54,6 +91,7 @@ def to_read(dcr: DailyCallReport) -> DCRRead:
)
for c in sorted(dcr.chemist_calls, key=lambda x: x.visit_time)
],
planned_visits=planned_visits(dcr),
)
@@ -61,6 +99,7 @@ def to_list_item(dcr: DailyCallReport) -> DCRListItem:
return DCRListItem(
id=dcr.id,
report_date=dcr.report_date,
report_type=dcr.report_type,
status=dcr.status,
mr_user_id=dcr.mr_user_id,
mr_name=dcr.mr.full_name,
+330 -52
View File
@@ -2,6 +2,22 @@
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 Manager; it is linked to that plan.
P3 Every planned doctor/chemist 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 Manager's own report (S1-S3):
S1 An Area 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 or chemist of that headquarters.
S3 There is no approval: submitting it makes it final (APPROVED, locked, PDF stored).
"""
import uuid
@@ -13,30 +29,37 @@ 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 assert_can_view_dcr, visible_hq_ids
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
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit
from app.reports.repository import DCRRepository
from app.reports.schemas import ChemistCallCreate, DCRCreate, DoctorCallCreate
from app.reports.schemas import ChemistCallCreate, DCRCreate, DoctorCallCreate, MissedVisitSet
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",
@@ -49,6 +72,15 @@ _AUDIT_FIELDS = [
]
#: 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.AM})}
_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()
@@ -65,13 +97,15 @@ class DCRService:
# Validation helpers
# ------------------------------------------------------------------
def _validate_report_date(self, report_date: date) -> None:
def _validate_report_date(self, report_date: date, report_type: ReportType) -> None:
today = local_today()
# V2 — no future reports.
if report_date > 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(
"Report date cannot be in the future",
{"report_date": report_date.isoformat(), "today": today.isoformat()},
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)
@@ -91,17 +125,49 @@ class DCRService:
{"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 _assigned_doctor_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]:
stmt = select(DoctorAssignment.doctor_id).where(
DoctorAssignment.mr_user_id == mr_user_id,
DoctorAssignment.effective_to.is_(None),
# A doctor the MR added is visitable only once the Area 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).where(
ChemistAssignment.mr_user_id == mr_user_id,
ChemistAssignment.effective_to.is_(None),
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())
@@ -111,12 +177,21 @@ class DCRService:
# V6 — only doctors currently assigned to this MR may be called.
if payload.doctor_id not in assigned:
raise ValidationError(
"Doctor is not assigned to this MR",
"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(
@@ -127,10 +202,11 @@ class DCRService:
dcr_id=dcr.id,
doctor_id=payload.doctor_id,
visit_time=payload.visit_time,
call_outcome=payload.call_outcome,
conversion_status=payload.conversion_status,
product_promote=_clean(payload.product_promote),
product_sample=_clean(payload.product_sample),
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,
)
@@ -139,7 +215,10 @@ class DCRService:
) -> ChemistCall:
if payload.chemist_id not in assigned:
raise ValidationError(
"Chemist is not assigned to this MR", {"chemist_id": str(payload.chemist_id)}
"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)})
@@ -158,30 +237,47 @@ class DCRService:
async def create(
self, data: DCRCreate, actor: User, ip: str | None = None
) -> DailyCallReport:
if actor.role != Role.MR or actor.headquarters_id is None:
if data.report_type == ReportType.SELF:
if actor.role != Role.AM:
raise ForbiddenError("Only an Area 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)
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):
if await self.repo.get_for_date(actor.id, data.report_date, data.report_type):
raise ConflictError(
"A report already exists for this date",
{"report_date": data.report_date.isoformat()},
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=actor.headquarters_id, # snapshot (A1)
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._assigned_doctor_ids(actor.id)
chemist_ids = await self._assigned_chemist_ids(actor.id)
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:
@@ -217,7 +313,8 @@ class DCRService:
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A report already exists for this MR and date", {"cause": "uq_dcr_mr_date"}
"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)
@@ -247,7 +344,7 @@ class DCRService:
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._assigned_doctor_ids(actor.id)
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)
@@ -264,6 +361,7 @@ class DCRService:
{"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,
@@ -279,7 +377,7 @@ class DCRService:
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._assigned_chemist_ids(actor.id)
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)
@@ -293,6 +391,7 @@ class DCRService:
{"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,
@@ -305,8 +404,8 @@ class DCRService:
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."""
if dcr.report_date == local_today():
"""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":
@@ -333,6 +432,79 @@ class DCRService:
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 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)")
if (payload.doctor_id is None) == (payload.chemist_id is None):
raise ValidationError("Give exactly one of doctor_id or chemist_id")
reason = _clean(payload.reason)
if reason is None:
raise ValidationError("Say briefly why the visit was missed")
target_id = payload.doctor_id or payload.chemist_id
line = next((p for p in planned_visits(dcr) if p.target_id == target_id), None)
if line is None:
raise ValidationError(
"This doctor or chemist is not on the plan", {"target_id": str(target_id)}
)
if line.status == "VISITED":
raise ConflictError(
"A visit is already recorded for this doctor or chemist; 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) == 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,
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), "reason": note.reason},
ip_address=ip,
)
await self.db.commit()
return await self.repo.get_full(dcr.id)
# ------------------------------------------------------------------
# Workflow transitions
# ------------------------------------------------------------------
@@ -344,19 +516,18 @@ class DCRService:
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:
from app.common.exceptions import ForbiddenError
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")
raise ForbiddenError("Only the owning MR can submit this report")
if dcr.report_type == ReportType.SELF:
return await self._finalise_self_report(dcr, actor, ip)
if dcr.status == DCRStatus.PENDING_AM:
return dcr # already submitted (a double click): nothing more to do
transition = assert_transition(dcr.status, WorkflowAction.SUBMIT, actor.role)
# V4 — at least one doctor call is required to submit.
if not dcr.doctor_calls:
raise ValidationError("A report must contain at least one doctor call to submit")
self._check_submit_contents(dcr)
self._check_submission_deadline(dcr.report_date)
before = snapshot(dcr, _AUDIT_FIELDS)
@@ -378,6 +549,36 @@ class DCRService:
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 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:
@@ -447,16 +648,33 @@ class DCRService:
await assert_can_view_dcr(self.db, actor, dcr)
return dcr
async def list_for(self, actor: User, **filters) -> list[DailyCallReport]:
if actor.role == Role.MR:
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 Manager's SELF list is their own reports, not their headquarters'.
if actor.role in FIELD_ROLES or (
actor.role == Role.AM and filters.get("report_type") == ReportType.SELF
):
return await self.repo.list_scoped(mr_user_id=actor.id, **filters)
hq_ids = await visible_hq_ids(self.db, actor)
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) -> dict[str, int]:
if actor.role == Role.MR:
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 visible_hq_ids(self.db, actor))
return await self.repo.status_counts(hq_ids=await self._hq_scope(actor, headquarters_id))
# ------------------------------------------------------------------
# Internals
@@ -468,13 +686,22 @@ class DCRService:
if dcr is None:
raise NotFoundError("Report not found", {"id": str(dcr_id)})
await assert_can_view_dcr(self.db, actor, dcr)
if actor.role != Role.MR or dcr.mr_user_id != actor.id:
from app.common.exceptions import ForbiddenError
raise ForbiddenError("Only the owning MR can modify report data")
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 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:
@@ -482,11 +709,62 @@ class DCRService:
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:
raise ValidationError("Plan at least one doctor or chemist 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 and chemist",
{"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 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,
) -> 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
):
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
stmt = select(AMHeadquarters.area_manager_user_id).where(
AMHeadquarters.headquarters_id == headquarters_id,
AMHeadquarters.effective_to.is_(None),
# Recorded only; any Area 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()