Production
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user