Production

This commit is contained in:
Shubhankar45
2026-09-22 06:23:46 +00:00
commit 8fdd20b29f
217 changed files with 31212 additions and 0 deletions
View File
+144
View File
@@ -0,0 +1,144 @@
"""The Daily Call Report and its call rows — the core artefact of the MVP."""
import uuid
from datetime import date, datetime, time
from sqlalchemy import (
CheckConstraint,
Date,
DateTime,
Enum,
ForeignKey,
String,
Text,
Time,
UniqueConstraint,
)
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.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"),
# An approved report must carry its approval timestamp, and nothing else may.
CheckConstraint(
"(status = 'APPROVED' AND approved_at IS NOT NULL) "
"OR (status <> 'APPROVED' AND approved_at IS NULL)",
name="ck_dcr_approved_at",
),
)
mr_user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
)
#: SNAPSHOT of the MR's headquarters at creation time. If the MR is later
#: transferred, historical reports keep the HQ they were filed under (A1).
headquarters_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False
)
report_date: Mapped[date] = mapped_column(Date, nullable=False)
status: Mapped[DCRStatus] = mapped_column(
Enum(DCRStatus, name="dcr_status_enum", native_enum=False, length=20),
default=DCRStatus.DRAFT,
nullable=False,
)
#: SNAPSHOT of the reviewing AM / approving GM, so an HQ handover never rewrites
#: history (report §5.5).
current_am_user_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT")
)
current_gm_user_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT")
)
mr_remarks: Mapped[str | None] = mapped_column(Text)
#: The printed form's "STOCKIST VISIT" and "ORDER" lines.
stockist_visit: Mapped[str | None] = mapped_column(String(200))
order_value: Mapped[str | None] = mapped_column(String(100))
return_reason: Mapped[str | None] = mapped_column(Text)
#: Which role sent it back — data, not a separate status (report §7.2).
returned_by_role: Mapped[Role | None] = mapped_column(
Enum(Role, name="role_enum", native_enum=False, length=10)
)
submitted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
approved_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
pdf_path: Mapped[str | None] = mapped_column(String(500))
mr: Mapped["User"] = relationship(foreign_keys=[mr_user_id]) # noqa: F821
headquarters: Mapped["Headquarters"] = relationship() # noqa: F821
doctor_calls: Mapped[list["DoctorCall"]] = relationship(
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
)
chemist_calls: Mapped[list["ChemistCall"]] = relationship(
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
)
@property
def is_locked(self) -> bool:
"""APPROVED is the lock. There is no separate LOCKED status (report §7.2)."""
return self.status == DCRStatus.APPROVED
class DoctorCall(Base, UUIDMixin, TimestampMixin):
__tablename__ = "doctor_call"
__table_args__ = (
# V5 / A11 — a doctor may appear only once per report.
UniqueConstraint("dcr_id", "doctor_id", name="uq_call_dcr_doctor"),
)
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] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("doctor.id", ondelete="RESTRICT"), nullable=False
)
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,
)
#: 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))
remarks: Mapped[str | None] = mapped_column(Text)
dcr: Mapped["DailyCallReport"] = relationship(back_populates="doctor_calls")
doctor: Mapped["Doctor"] = relationship(lazy="selectin") # noqa: F821
class ChemistCall(Base, UUIDMixin, TimestampMixin):
__tablename__ = "chemist_call"
__table_args__ = (
UniqueConstraint("dcr_id", "chemist_id", name="uq_call_dcr_chemist"),
)
dcr_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey("daily_call_report.id", ondelete="CASCADE"),
nullable=False,
)
chemist_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("chemist.id", ondelete="RESTRICT"), nullable=False
)
visit_time: Mapped[time] = mapped_column(Time, nullable=False)
#: The printed form's "POB" column.
pob: Mapped[str | None] = mapped_column(String(100))
remarks: Mapped[str | None] = mapped_column(Text)
dcr: Mapped["DailyCallReport"] = relationship(back_populates="chemist_calls")
chemist: Mapped["Chemist"] = relationship(lazy="selectin") # noqa: F821
+99
View File
@@ -0,0 +1,99 @@
import uuid
from datetime import date
from sqlalchemy import func, select
from sqlalchemy.orm import selectinload
from app.common.enums import DCRStatus
from app.common.repository import BaseRepository
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall
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.mr),
selectinload(DailyCallReport.headquarters),
)
# 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
) -> 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,
)
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,
):
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 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,
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,
)
.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}
+204
View File
@@ -0,0 +1,204 @@
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, 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,
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"),
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),
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."""
reports = await DCRService(db).list_for(
current_user,
status=status_filter,
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(
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))
@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)
filename = f"DCR-{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)),
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)),
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)),
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)),
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)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
await DCRService(db).delete_call(dcr_id, call_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)),
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))
)
+126
View File
@@ -0,0 +1,126 @@
import uuid
from datetime import date, datetime, time
from pydantic import BaseModel, ConfigDict, Field
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, Role
from app.config.settings import settings
class DoctorCallCreate(BaseModel):
doctor_id: uuid.UUID
visit_time: time
call_outcome: CallOutcome
#: 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)
remarks: str | None = Field(default=None, max_length=2000)
class ChemistCallCreate(BaseModel):
chemist_id: uuid.UUID
visit_time: time
pob: str | None = Field(default=None, max_length=100)
remarks: str | None = Field(default=None, max_length=2000)
class DoctorCallRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
doctor_id: uuid.UUID
doctor_name: str
doctor_speciality: str | None
is_core_doctor: bool
visit_time: time
call_outcome: CallOutcome
conversion_status: ConversionStatus | None
product_promote: str | None
product_sample: str | None
remarks: str | None
class ChemistCallRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
chemist_id: uuid.UUID
chemist_name: str
visit_time: time
pob: str | None
remarks: str | None
class DCRCreate(BaseModel):
report_date: date
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)
class DCRUpdate(BaseModel):
mr_remarks: str | None = Field(default=None, max_length=2000)
stockist_visit: str | None = Field(default=None, max_length=200)
order_value: str | None = Field(default=None, max_length=100)
class ReturnRequest(BaseModel):
"""V8 — a manager must say WHY. This reason is what makes the audit trail useful."""
reason: str = Field(min_length=settings.MIN_RETURN_REASON_LENGTH, max_length=2000)
class ApproveRequest(BaseModel):
comment: str | None = Field(default=None, max_length=2000)
class DCRListItem(BaseModel):
"""Row for S2/S6 — the list screens that replaced the cut dashboards."""
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
report_date: date
status: DCRStatus
mr_user_id: uuid.UUID
mr_name: str
headquarters_id: uuid.UUID
headquarters_name: str
doctor_call_count: int
chemist_call_count: int
submitted_at: datetime | None
approved_at: datetime | None
returned_by_role: Role | None
class DCRRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
mr_user_id: uuid.UUID
mr_name: str
employee_code: str
headquarters_id: uuid.UUID
headquarters_name: str
report_date: date
status: DCRStatus
is_locked: bool
mr_remarks: str | None
stockist_visit: str | None
order_value: str | None
return_reason: str | None
returned_by_role: Role | None
submitted_at: datetime | None
approved_at: datetime | None
doctor_calls: list[DoctorCallRead]
chemist_calls: list[ChemistCallRead]
class StatusCounts(BaseModel):
"""Header counts on the list screens — the cheap replacement for dashboards."""
DRAFT: int = 0
PENDING_AM: int = 0
RETURNED: int = 0
APPROVED: int = 0
+74
View File
@@ -0,0 +1,74 @@
"""ORM → response-schema mapping for reports."""
from app.reports.models import DailyCallReport
from app.reports.schemas import (
ChemistCallRead,
DCRListItem,
DCRRead,
DoctorCallRead,
)
def to_read(dcr: DailyCallReport) -> DCRRead:
return DCRRead(
id=dcr.id,
mr_user_id=dcr.mr_user_id,
mr_name=dcr.mr.full_name,
employee_code=dcr.mr.employee_code,
headquarters_id=dcr.headquarters_id,
headquarters_name=dcr.headquarters.name,
report_date=dcr.report_date,
status=dcr.status,
is_locked=dcr.is_locked,
mr_remarks=dcr.mr_remarks,
stockist_visit=dcr.stockist_visit,
order_value=dcr.order_value,
return_reason=dcr.return_reason,
returned_by_role=dcr.returned_by_role,
submitted_at=dcr.submitted_at,
approved_at=dcr.approved_at,
doctor_calls=[
DoctorCallRead(
id=c.id,
doctor_id=c.doctor_id,
doctor_name=c.doctor.name,
doctor_speciality=c.doctor.speciality,
is_core_doctor=c.doctor.is_core_doctor,
visit_time=c.visit_time,
call_outcome=c.call_outcome,
conversion_status=c.conversion_status,
product_promote=c.product_promote,
product_sample=c.product_sample,
remarks=c.remarks,
)
for c in sorted(dcr.doctor_calls, key=lambda x: x.visit_time)
],
chemist_calls=[
ChemistCallRead(
id=c.id,
chemist_id=c.chemist_id,
chemist_name=c.chemist.name,
visit_time=c.visit_time,
pob=c.pob,
remarks=c.remarks,
)
for c in sorted(dcr.chemist_calls, key=lambda x: x.visit_time)
],
)
def to_list_item(dcr: DailyCallReport) -> DCRListItem:
return DCRListItem(
id=dcr.id,
report_date=dcr.report_date,
status=dcr.status,
mr_user_id=dcr.mr_user_id,
mr_name=dcr.mr.full_name,
headquarters_id=dcr.headquarters_id,
headquarters_name=dcr.headquarters.name,
doctor_call_count=len(dcr.doctor_calls),
chemist_call_count=len(dcr.chemist_calls),
submitted_at=dcr.submitted_at,
approved_at=dcr.approved_at,
returned_by_role=dcr.returned_by_role,
)
+492
View File
@@ -0,0 +1,492 @@
"""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.
"""
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 assert_can_view_dcr, visible_hq_ids
from app.chemists.models import Chemist, ChemistAssignment
from app.common.enums import (
AuditAction,
DCRStatus,
EntityType,
Role,
WorkflowAction,
)
from app.common.exceptions import (
ConflictError,
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.repository import DCRRepository
from app.reports.schemas import ChemistCallCreate, DCRCreate, DoctorCallCreate
from app.users.models import User
#: Audit fields — the columns worth recording on a state change.
_AUDIT_FIELDS = [
"status",
"report_date",
"mr_remarks",
"stockist_visit",
"order_value",
"return_reason",
"returned_by_role",
"submitted_at",
"approved_at",
]
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) -> None:
today = local_today()
# V2 — no future reports.
if report_date > today:
raise ValidationError(
"Report date cannot be in the future",
{"report_date": report_date.isoformat(), "today": today.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 _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),
)
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),
)
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 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)})
# 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=payload.call_outcome,
conversion_status=payload.conversion_status,
product_promote=_clean(payload.product_promote),
product_sample=_clean(payload.product_sample),
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 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,
)
# ------------------------------------------------------------------
# Commands
# ------------------------------------------------------------------
async def create(
self, data: DCRCreate, actor: User, ip: str | None = None
) -> DailyCallReport:
if actor.role != Role.MR or actor.headquarters_id is None:
raise ValidationError("Only an MR with a headquarters can create a report")
self._validate_report_date(data.report_date)
# 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):
raise ConflictError(
"A report already exists for this date",
{"report_date": data.report_date.isoformat()},
)
dcr = DailyCallReport(
id=uuid.uuid4(),
mr_user_id=actor.id,
headquarters_id=actor.headquarters_id, # snapshot (A1)
report_date=data.report_date,
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)
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 already exists for this MR and date", {"cause": "uq_dcr_mr_date"}
) 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._assigned_doctor_ids(actor.id)
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.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._assigned_chemist_ids(actor.id)
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.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)
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():
# 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)
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)
# ------------------------------------------------------------------
# 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:
from app.common.exceptions import ForbiddenError
raise ForbiddenError("Only the owning MR can submit this report")
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_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 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 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.AM:
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 list_for(self, actor: User, **filters) -> list[DailyCallReport]:
if actor.role == Role.MR:
return await self.repo.list_scoped(mr_user_id=actor.id, **filters)
hq_ids = await visible_hq_ids(self.db, actor)
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:
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))
# ------------------------------------------------------------------
# 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 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")
assert_editable(dcr.status)
return dcr
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
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),
)
return (await self.db.execute(stmt)).scalars().first()