Server backup 2026-11-07 of uncommitted work in projects/pharma-web-celtic
Snapshot of the working tree on srv1071960 (branch main), taken during server cleanup. .env files, node_modules, builds, logs and media were excluded.
This commit is contained in:
+125
-34
@@ -7,16 +7,19 @@ 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
|
||||
APPROVED by the Area Business Manager; it is linked to that plan.
|
||||
P3 Every planned doctor/chemist/stockist must, before submit, either have a visit recorded on
|
||||
the end-of-day report or a short note saying why it was missed.
|
||||
P4 Recording a visit for a doctor/chemist drops any "missed" note for them.
|
||||
P5 Visits not on the plan may still be added to the end-of-day report.
|
||||
|
||||
Area Manager's own report (S1-S3):
|
||||
S1 An Area Manager files one SELF report per date, for one headquarters they manage;
|
||||
Area Business Manager's own report (S1-S3):
|
||||
S1 An Area Business Manager files one SELF report per date, for one headquarters they manage;
|
||||
it needs no plan.
|
||||
S2 Its visits may be to any active doctor or chemist of that headquarters.
|
||||
S2 Its visits may be to any active doctor, chemist or stockist of that headquarters.
|
||||
|
||||
Stockists are not assigned to an MR: an MR (or SFE) may visit any active stockist of the
|
||||
headquarters they cover.
|
||||
S3 There is no approval: submitting it makes it final (APPROVED, locked, PDF stored).
|
||||
"""
|
||||
|
||||
@@ -51,9 +54,16 @@ from app.common.exceptions import (
|
||||
from app.common.utils import local_now, local_today, snapshot, utcnow
|
||||
from app.config.settings import settings
|
||||
from app.doctors.models import Doctor, DoctorAssignment
|
||||
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit
|
||||
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit, StockistCall
|
||||
from app.reports.repository import DCRRepository
|
||||
from app.reports.schemas import ChemistCallCreate, DCRCreate, DoctorCallCreate, MissedVisitSet
|
||||
from app.reports.schemas import (
|
||||
ChemistCallCreate,
|
||||
DCRCreate,
|
||||
DoctorCallCreate,
|
||||
MissedVisitSet,
|
||||
StockistCallCreate,
|
||||
)
|
||||
from app.stockists.models import Stockist
|
||||
from app.reports.serializers import planned_visits
|
||||
from app.users.models import User
|
||||
|
||||
@@ -73,7 +83,7 @@ _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})}
|
||||
_OWNER_ROLE = {ReportType.PLAN: FIELD_ROLES, ReportType.ACTUAL: FIELD_ROLES, ReportType.SELF: frozenset({Role.ABM})}
|
||||
_LABEL = {
|
||||
ReportType.PLAN: "Daily Call Report (Plan)",
|
||||
ReportType.ACTUAL: "Daily Call Report (Done)",
|
||||
@@ -146,8 +156,23 @@ class DCRService:
|
||||
)
|
||||
return set((await self.db.execute(stmt)).scalars().all())
|
||||
|
||||
async def _allowed_stockist_ids(self, dcr: DailyCallReport) -> set[uuid.UUID]:
|
||||
"""Active stockists of the report's headquarters (SELF), or of every headquarters
|
||||
the MR / SFE covers."""
|
||||
hq_ids = (
|
||||
{dcr.headquarters_id}
|
||||
if dcr.report_type == ReportType.SELF
|
||||
else dcr.mr.covered_headquarter_ids or {dcr.headquarters_id}
|
||||
)
|
||||
stmt = select(Stockist.id).where(
|
||||
Stockist.headquarters_id.in_(hq_ids),
|
||||
Stockist.is_active.is_(True),
|
||||
Stockist.approval_status == MasterApproval.APPROVED,
|
||||
)
|
||||
return set((await self.db.execute(stmt)).scalars().all())
|
||||
|
||||
async def _assigned_doctor_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]:
|
||||
# A doctor the MR added is visitable only once the Area Manager has approved it.
|
||||
# A doctor the MR added is visitable only once the Area Business Manager has approved it.
|
||||
stmt = (
|
||||
select(DoctorAssignment.doctor_id)
|
||||
.join(Doctor, Doctor.id == DoctorAssignment.doctor_id)
|
||||
@@ -230,6 +255,25 @@ class DCRService:
|
||||
remarks=payload.remarks,
|
||||
)
|
||||
|
||||
async def _build_stockist_call(
|
||||
self, dcr: DailyCallReport, payload: StockistCallCreate, allowed: set[uuid.UUID]
|
||||
) -> StockistCall:
|
||||
if payload.stockist_id not in allowed:
|
||||
raise ValidationError(
|
||||
"Stockist is not in this report's headquarters"
|
||||
if dcr.report_type == ReportType.SELF
|
||||
else "Stockist is not in a headquarters you cover",
|
||||
{"stockist_id": str(payload.stockist_id)},
|
||||
)
|
||||
is_plan = dcr.report_type == ReportType.PLAN
|
||||
return StockistCall(
|
||||
dcr_id=dcr.id,
|
||||
stockist_id=payload.stockist_id,
|
||||
visit_time=payload.visit_time,
|
||||
pob=None if is_plan else _clean(payload.pob),
|
||||
remarks=payload.remarks,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Commands
|
||||
# ------------------------------------------------------------------
|
||||
@@ -238,8 +282,8 @@ class DCRService:
|
||||
self, data: DCRCreate, actor: User, ip: str | None = None
|
||||
) -> DailyCallReport:
|
||||
if data.report_type == ReportType.SELF:
|
||||
if actor.role != Role.AM:
|
||||
raise ForbiddenError("Only an Area Manager files a Daily Call Report (Self)")
|
||||
if actor.role != Role.ABM:
|
||||
raise ForbiddenError("Only an Area Business Manager files a Daily Call Report (Self)")
|
||||
headquarters_id = await self._self_report_hq(actor, data.headquarters_id)
|
||||
elif actor.role not in FIELD_ROLES:
|
||||
raise ForbiddenError("Only an MR files a Daily Call Report (Plan) or (Done)")
|
||||
@@ -403,6 +447,36 @@ class DCRService:
|
||||
await self.db.commit()
|
||||
return await self.repo.get_full(dcr.id)
|
||||
|
||||
async def add_stockist_call(
|
||||
self, dcr_id: uuid.UUID, payload: StockistCallCreate, actor: User, ip: str | None = None
|
||||
) -> DailyCallReport:
|
||||
dcr = await self._get_owned_editable(dcr_id, actor)
|
||||
allowed = await self._allowed_stockist_ids(dcr)
|
||||
call = await self._build_stockist_call(dcr, payload, allowed)
|
||||
self._validate_visit_time(dcr, payload.visit_time)
|
||||
self.db.add(call)
|
||||
|
||||
try:
|
||||
await self.db.flush()
|
||||
except IntegrityError as exc:
|
||||
await self.db.rollback()
|
||||
raise ConflictError(
|
||||
"This stockist has already been called on this report",
|
||||
{"stockist_id": str(payload.stockist_id), "cause": "uq_call_dcr_stockist"},
|
||||
) from exc
|
||||
|
||||
await self._drop_missed_note(dcr, stockist_id=payload.stockist_id)
|
||||
await self.audit.log(
|
||||
actor_user_id=actor.id,
|
||||
entity_type=EntityType.DCR,
|
||||
entity_id=dcr.id,
|
||||
action=AuditAction.UPDATE,
|
||||
after={"added_stockist_call": str(payload.stockist_id)},
|
||||
ip_address=ip,
|
||||
)
|
||||
await self.db.commit()
|
||||
return await self.repo.get_full(dcr.id)
|
||||
|
||||
def _validate_visit_time(self, dcr: DailyCallReport, visit_time) -> None:
|
||||
"""V11 — a visit time on today's report cannot be in the future (P1: plans excepted)."""
|
||||
if dcr.report_type != ReportType.PLAN and dcr.report_date == local_today():
|
||||
@@ -417,7 +491,11 @@ class DCRService:
|
||||
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)
|
||||
call = (
|
||||
await self.db.get(DoctorCall, call_id)
|
||||
or await self.db.get(ChemistCall, call_id)
|
||||
or await self.db.get(StockistCall, call_id)
|
||||
)
|
||||
if call is None or call.dcr_id != dcr.id:
|
||||
raise NotFoundError("Call not found on this report", {"call_id": str(call_id)})
|
||||
await self.db.delete(call)
|
||||
@@ -435,30 +513,36 @@ class DCRService:
|
||||
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."""
|
||||
"""P3 — record (or reword) why a planned doctor/chemist/stockist was not visited."""
|
||||
dcr = await self._get_owned_editable(dcr_id, actor)
|
||||
if dcr.report_type != ReportType.ACTUAL or dcr.plan is None:
|
||||
raise ValidationError("Missed-visit notes belong on a Daily Call Report (Done)")
|
||||
if (payload.doctor_id is None) == (payload.chemist_id is None):
|
||||
raise ValidationError("Give exactly one of doctor_id or chemist_id")
|
||||
targets = [t for t in (payload.doctor_id, payload.chemist_id, payload.stockist_id) if t]
|
||||
if len(targets) != 1:
|
||||
raise ValidationError("Give exactly one of doctor_id, chemist_id or stockist_id")
|
||||
reason = _clean(payload.reason)
|
||||
if reason is None:
|
||||
raise ValidationError("Say briefly why the visit was missed")
|
||||
|
||||
target_id = payload.doctor_id or payload.chemist_id
|
||||
target_id = targets[0]
|
||||
line = next((p for p in planned_visits(dcr) if p.target_id == target_id), None)
|
||||
if line is None:
|
||||
raise ValidationError(
|
||||
"This doctor or chemist is not on the plan", {"target_id": str(target_id)}
|
||||
"This doctor, chemist or stockist is not on the plan", {"target_id": str(target_id)}
|
||||
)
|
||||
if line.status == "VISITED":
|
||||
raise ConflictError(
|
||||
"A visit is already recorded for this doctor or chemist; remove it first",
|
||||
"A visit is already recorded for this doctor, chemist or stockist; remove it first",
|
||||
{"target_id": str(target_id)},
|
||||
)
|
||||
|
||||
note = next(
|
||||
(m for m in dcr.missed_visits if (m.doctor_id or m.chemist_id) == target_id), None
|
||||
(
|
||||
m
|
||||
for m in dcr.missed_visits
|
||||
if (m.doctor_id or m.chemist_id or m.stockist_id) == target_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
before = {"reason": note.reason} if note else None
|
||||
if note is None:
|
||||
@@ -467,6 +551,7 @@ class DCRService:
|
||||
dcr_id=dcr.id,
|
||||
doctor_id=payload.doctor_id,
|
||||
chemist_id=payload.chemist_id,
|
||||
stockist_id=payload.stockist_id,
|
||||
reason=reason,
|
||||
)
|
||||
)
|
||||
@@ -499,7 +584,10 @@ class DCRService:
|
||||
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},
|
||||
before={
|
||||
"missed_visit": str(note.doctor_id or note.chemist_id or note.stockist_id),
|
||||
"reason": note.reason,
|
||||
},
|
||||
ip_address=ip,
|
||||
)
|
||||
await self.db.commit()
|
||||
@@ -522,7 +610,7 @@ class DCRService:
|
||||
if dcr.report_type == ReportType.SELF:
|
||||
return await self._finalise_self_report(dcr, actor, ip)
|
||||
|
||||
if dcr.status == DCRStatus.PENDING_AM:
|
||||
if dcr.status == DCRStatus.PENDING_ABM:
|
||||
return dcr # already submitted (a double click): nothing more to do
|
||||
|
||||
transition = assert_transition(dcr.status, WorkflowAction.SUBMIT, actor.role)
|
||||
@@ -552,7 +640,7 @@ class DCRService:
|
||||
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."""
|
||||
"""S3 — an Area Business Manager's own report is final once submitted; nobody approves it."""
|
||||
if dcr.status == DCRStatus.APPROVED:
|
||||
return dcr # already submitted (a double click)
|
||||
assert_editable(dcr.status)
|
||||
@@ -606,9 +694,9 @@ class DCRService:
|
||||
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."""
|
||||
"""Area Business Manager final approval. APPROVED is terminal and immutable."""
|
||||
dcr = await self._get_in_scope(dcr_id, actor)
|
||||
if dcr.status == DCRStatus.APPROVED and actor.role == Role.AM:
|
||||
if dcr.status == DCRStatus.APPROVED and actor.role == Role.ABM:
|
||||
return dcr # already approved (a double click): the report stays as it is
|
||||
transition = assert_transition(dcr.status, WorkflowAction.APPROVE, actor.role)
|
||||
|
||||
@@ -661,9 +749,9 @@ class DCRService:
|
||||
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'.
|
||||
# An Area Business 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
|
||||
actor.role == Role.ABM and filters.get("report_type") == ReportType.SELF
|
||||
):
|
||||
return await self.repo.list_scoped(mr_user_id=actor.id, **filters)
|
||||
hq_ids = await self._hq_scope(actor, headquarters_id)
|
||||
@@ -692,7 +780,7 @@ class DCRService:
|
||||
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."""
|
||||
"""S1 — one of the headquarters this Area Business Manager manages; implied when there is one."""
|
||||
managed = await active_hq_ids_for_am(self.db, actor.id)
|
||||
if headquarters_id is None and len(managed) == 1:
|
||||
return next(iter(managed))
|
||||
@@ -711,14 +799,14 @@ class DCRService:
|
||||
|
||||
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")
|
||||
if not dcr.doctor_calls and not dcr.chemist_calls and not dcr.stockist_calls:
|
||||
raise ValidationError("Plan at least one doctor, chemist or stockist visit to submit")
|
||||
return
|
||||
# P3 — every planned visit is either recorded or explained.
|
||||
pending = [p for p in planned_visits(dcr) if p.status == "PENDING"]
|
||||
if pending:
|
||||
raise ValidationError(
|
||||
"Record a visit or add a missed-visit note for every planned doctor and chemist",
|
||||
"Record a visit or add a missed-visit note for every planned doctor, chemist and stockist",
|
||||
{"pending": [p.name for p in pending]},
|
||||
)
|
||||
# V4 — at least one doctor call, unless the planned visits were all explained.
|
||||
@@ -737,7 +825,7 @@ class DCRService:
|
||||
if plan.status != DCRStatus.APPROVED:
|
||||
raise ValidationError(
|
||||
"Your Daily Call Report (Plan) for this date must be approved "
|
||||
"by the Area Manager first",
|
||||
"by the Area Business Manager first",
|
||||
{"report_date": report_date.isoformat(), "plan_status": plan.status.value},
|
||||
)
|
||||
return plan
|
||||
@@ -747,18 +835,21 @@ class DCRService:
|
||||
dcr: DailyCallReport,
|
||||
doctor_id: uuid.UUID | None = None,
|
||||
chemist_id: uuid.UUID | None = None,
|
||||
stockist_id: uuid.UUID | None = None,
|
||||
) -> None:
|
||||
"""P4 — a recorded visit replaces any note saying it was missed."""
|
||||
for note in dcr.missed_visits:
|
||||
if (doctor_id and note.doctor_id == doctor_id) or (
|
||||
chemist_id and note.chemist_id == chemist_id
|
||||
if (
|
||||
(doctor_id and note.doctor_id == doctor_id)
|
||||
or (chemist_id and note.chemist_id == chemist_id)
|
||||
or (stockist_id and note.stockist_id == stockist_id)
|
||||
):
|
||||
await self.db.delete(note)
|
||||
|
||||
async def _current_am_for_hq(self, headquarters_id: uuid.UUID) -> uuid.UUID | None:
|
||||
from app.organization.models import AMHeadquarters
|
||||
|
||||
# Recorded only; any Area Manager of the headquarters may act on the report.
|
||||
# Recorded only; any Area Business Manager of the headquarters may act on the report.
|
||||
stmt = (
|
||||
select(AMHeadquarters.area_manager_user_id)
|
||||
.where(
|
||||
|
||||
Reference in New Issue
Block a user