--
This commit is contained in:
@@ -15,6 +15,7 @@ from sqlalchemy import Boolean, Date, ForeignKey, Index, String, UniqueConstrain
|
||||
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.common.enums import MasterApproval
|
||||
from app.database.base import Base, TimestampMixin, UUIDMixin
|
||||
|
||||
|
||||
@@ -35,9 +36,26 @@ class Doctor(Base, UUIDMixin, TimestampMixin):
|
||||
qualification: Mapped[str | None] = mapped_column(String(100))
|
||||
clinic_address: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
contact_number: Mapped[str | None] = mapped_column(String(20))
|
||||
date_of_birth: Mapped[date | None] = mapped_column(Date)
|
||||
#: Core doctors are the high-value targets tracked for conversion.
|
||||
is_core_doctor: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
#: PENDING until the Area Manager approves one an MR added; only APPROVED ones are listed or visited.
|
||||
approval_status: Mapped[str] = mapped_column(
|
||||
String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False
|
||||
)
|
||||
#: The MR who asked for it (None for one the administrator created).
|
||||
requested_by_user_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL")
|
||||
)
|
||||
rejection_reason: Mapped[str | None] = mapped_column(String(500))
|
||||
requested_by: Mapped["User | None"] = relationship( # noqa: F821
|
||||
lazy="selectin", foreign_keys=[requested_by_user_id]
|
||||
)
|
||||
|
||||
@property
|
||||
def requested_by_name(self) -> str | None:
|
||||
return self.requested_by.full_name if self.requested_by else None
|
||||
|
||||
assignments: Mapped[list["DoctorAssignment"]] = relationship(back_populates="doctor")
|
||||
|
||||
|
||||
+34
-3
@@ -7,7 +7,7 @@ from app.auth.dependencies import client_ip, get_current_user, require_role
|
||||
from app.common.enums import Role
|
||||
from app.database.session import get_db
|
||||
from app.doctors.models import Doctor
|
||||
from app.doctors.schemas import AssignToMR, DoctorCreate, DoctorRead, DoctorUpdate
|
||||
from app.doctors.schemas import AssignToMR, DoctorCreate, DoctorRead, DoctorUpdate, RejectMaster
|
||||
from app.doctors.service import DoctorService
|
||||
from app.users.models import User
|
||||
|
||||
@@ -26,10 +26,10 @@ async def list_doctors(
|
||||
async def create_doctor(
|
||||
payload: DoctorCreate,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||
current_user: User = Depends(require_role(Role.ADMIN, Role.MR)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> Doctor:
|
||||
"""Only an Administrator can create a doctor (MR, AM and GM cannot)."""
|
||||
"""An Administrator, or an MR within their own headquarters (AM and GM cannot)."""
|
||||
return await DoctorService(db).create(payload, current_user, client_ip(request))
|
||||
|
||||
|
||||
@@ -62,3 +62,34 @@ async def assign_doctor(
|
||||
"mr_user_id": assignment.mr_user_id,
|
||||
"effective_from": assignment.effective_from,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/requests", response_model=list[DoctorRead])
|
||||
async def list_doctor_requests(
|
||||
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||
) -> list[Doctor]:
|
||||
"""Doctors an MR added that wait for the Area Manager: an MR sees their own (with any
|
||||
rejected and why), an Area Manager what waits for them, the administrator and GM all."""
|
||||
return await DoctorService(db).requests_for(current_user)
|
||||
|
||||
|
||||
@router.post("/{doctor_id}/approve", response_model=DoctorRead)
|
||||
async def approve_doctor(
|
||||
doctor_id: uuid.UUID,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> Doctor:
|
||||
"""The Area Manager of its headquarters adds it to the list, assigned to the MR who asked."""
|
||||
return await DoctorService(db).review(doctor_id, True, None, current_user, client_ip(request))
|
||||
|
||||
|
||||
@router.post("/{doctor_id}/reject", response_model=DoctorRead)
|
||||
async def reject_doctor(
|
||||
doctor_id: uuid.UUID,
|
||||
payload: RejectMaster,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> Doctor:
|
||||
return await DoctorService(db).review(doctor_id, False, payload.reason, current_user, client_ip(request))
|
||||
|
||||
+26
-2
@@ -1,7 +1,13 @@
|
||||
import uuid
|
||||
from datetime import date
|
||||
from datetime import date, datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
def _not_in_future(value: date | None) -> date | None:
|
||||
if value is not None and value > date.today():
|
||||
raise ValueError("date_of_birth cannot be in the future")
|
||||
return value
|
||||
|
||||
|
||||
class DoctorCreate(BaseModel):
|
||||
@@ -11,8 +17,11 @@ class DoctorCreate(BaseModel):
|
||||
speciality: str | None = Field(default=None, max_length=100)
|
||||
qualification: str | None = Field(default=None, max_length=100)
|
||||
contact_number: str | None = Field(default=None, max_length=20)
|
||||
date_of_birth: date | None = None
|
||||
is_core_doctor: bool = False
|
||||
|
||||
_check_dob = field_validator("date_of_birth")(_not_in_future)
|
||||
|
||||
|
||||
class DoctorUpdate(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=2, max_length=200)
|
||||
@@ -20,9 +29,12 @@ class DoctorUpdate(BaseModel):
|
||||
speciality: str | None = Field(default=None, max_length=100)
|
||||
qualification: str | None = Field(default=None, max_length=100)
|
||||
contact_number: str | None = Field(default=None, max_length=20)
|
||||
date_of_birth: date | None = None
|
||||
is_core_doctor: bool | None = None
|
||||
is_active: bool | None = None
|
||||
|
||||
_check_dob = field_validator("date_of_birth")(_not_in_future)
|
||||
|
||||
|
||||
class DoctorRead(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
@@ -34,10 +46,22 @@ class DoctorRead(BaseModel):
|
||||
speciality: str | None
|
||||
qualification: str | None
|
||||
contact_number: str | None
|
||||
date_of_birth: date | None
|
||||
is_core_doctor: bool
|
||||
is_active: bool
|
||||
#: PENDING / APPROVED / REJECTED — see app/common/master_approval.py.
|
||||
approval_status: str
|
||||
rejection_reason: str | None
|
||||
requested_by_name: str | None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class AssignToMR(BaseModel):
|
||||
mr_user_id: uuid.UUID
|
||||
effective_from: date | None = None
|
||||
|
||||
|
||||
class RejectMaster(BaseModel):
|
||||
"""Why the Area Manager refused a doctor or chemist an MR added — shown to that MR."""
|
||||
|
||||
reason: str = Field(min_length=3, max_length=500)
|
||||
|
||||
+69
-8
@@ -7,14 +7,22 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.audit.service import AuditService
|
||||
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
|
||||
from app.common.enums import AuditAction, EntityType, Role
|
||||
from app.common import master_approval
|
||||
from app.common.enums import AuditAction, EntityType, MasterApproval, Role, FIELD_ROLES
|
||||
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
||||
from app.common.utils import snapshot
|
||||
from app.doctors.models import Doctor, DoctorAssignment
|
||||
from app.doctors.schemas import DoctorCreate, DoctorUpdate
|
||||
from app.users.models import User
|
||||
|
||||
_AUDIT_FIELDS = ["name", "clinic_address", "speciality", "is_core_doctor", "is_active"]
|
||||
_AUDIT_FIELDS = [
|
||||
"name",
|
||||
"clinic_address",
|
||||
"speciality",
|
||||
"date_of_birth",
|
||||
"is_core_doctor",
|
||||
"is_active",
|
||||
]
|
||||
|
||||
|
||||
class DoctorService:
|
||||
@@ -23,10 +31,35 @@ class DoctorService:
|
||||
self.audit = AuditService(db)
|
||||
|
||||
async def create(self, data: DoctorCreate, actor: User, ip: str | None = None) -> Doctor:
|
||||
# A2/A3 — masters are owned by ADMIN/GM. An MR cannot create a doctor.
|
||||
# A2/A3 — masters belong to a headquarters. An MR may add one only to their own.
|
||||
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
||||
|
||||
doctor = Doctor(**data.model_dump())
|
||||
values = data.model_dump()
|
||||
# Added by an MR: it waits for the Area Manager. One they were refused is sent again.
|
||||
twin = None
|
||||
if actor.role in FIELD_ROLES:
|
||||
twin = await master_approval.rejected_twin(
|
||||
self.db, Doctor, {k: values[k] for k in ('headquarters_id', 'name', 'clinic_address')}
|
||||
)
|
||||
if twin is not None:
|
||||
await master_approval.resubmit(self.db, twin, values, actor, DoctorAssignment, "doctor_id")
|
||||
await self.audit.log(
|
||||
actor_user_id=actor.id,
|
||||
entity_type=EntityType.DOCTOR,
|
||||
entity_id=twin.id,
|
||||
action=AuditAction.SUBMIT,
|
||||
after=snapshot(twin, _AUDIT_FIELDS),
|
||||
ip_address=ip,
|
||||
)
|
||||
await self.db.commit()
|
||||
await self.db.refresh(twin)
|
||||
return twin
|
||||
|
||||
doctor = Doctor(
|
||||
**values,
|
||||
approval_status=master_approval.initial_status(actor),
|
||||
requested_by_user_id=actor.id if actor.role in FIELD_ROLES else None,
|
||||
)
|
||||
self.db.add(doctor)
|
||||
try:
|
||||
await self.db.flush()
|
||||
@@ -45,7 +78,22 @@ class DoctorService:
|
||||
after=snapshot(doctor, _AUDIT_FIELDS),
|
||||
ip_address=ip,
|
||||
)
|
||||
# An MR only sees assigned doctors, so the one they add is assigned to them.
|
||||
if actor.role in FIELD_ROLES:
|
||||
start = date.today()
|
||||
self.db.add(
|
||||
DoctorAssignment(doctor_id=doctor.id, mr_user_id=actor.id, effective_from=start)
|
||||
)
|
||||
await self.audit.log(
|
||||
actor_user_id=actor.id,
|
||||
entity_type=EntityType.DOCTOR,
|
||||
entity_id=doctor.id,
|
||||
action=AuditAction.ASSIGN,
|
||||
after={"mr_user_id": str(actor.id), "effective_from": start.isoformat()},
|
||||
ip_address=ip,
|
||||
)
|
||||
await self.db.commit()
|
||||
await self.db.refresh(doctor)
|
||||
return doctor
|
||||
|
||||
async def update(
|
||||
@@ -74,7 +122,7 @@ class DoctorService:
|
||||
|
||||
async def list_for(self, actor: User) -> list[Doctor]:
|
||||
"""An MR sees ONLY doctors currently assigned to them (R5)."""
|
||||
if actor.role == Role.MR:
|
||||
if actor.role in FIELD_ROLES:
|
||||
stmt = (
|
||||
select(Doctor)
|
||||
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
|
||||
@@ -82,13 +130,14 @@ class DoctorService:
|
||||
DoctorAssignment.mr_user_id == actor.id,
|
||||
DoctorAssignment.effective_to.is_(None),
|
||||
Doctor.is_active.is_(True),
|
||||
Doctor.approval_status == MasterApproval.APPROVED,
|
||||
)
|
||||
.order_by(Doctor.name)
|
||||
)
|
||||
return list((await self.db.execute(stmt)).scalars().all())
|
||||
|
||||
allowed = await visible_hq_ids(self.db, actor)
|
||||
stmt = select(Doctor).order_by(Doctor.name)
|
||||
stmt = select(Doctor).where(Doctor.approval_status == MasterApproval.APPROVED).order_by(Doctor.name)
|
||||
if allowed is not None:
|
||||
stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None]))
|
||||
return list((await self.db.execute(stmt)).scalars().all())
|
||||
@@ -105,14 +154,16 @@ class DoctorService:
|
||||
if doctor is None:
|
||||
raise NotFoundError("Doctor not found")
|
||||
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
||||
if doctor.approval_status != MasterApproval.APPROVED:
|
||||
raise ValidationError("This doctor is still waiting for the Area Manager's approval")
|
||||
|
||||
mr = await self.db.get(User, mr_user_id)
|
||||
if mr is None:
|
||||
raise NotFoundError("MR not found")
|
||||
if mr.role != Role.MR:
|
||||
if mr.role not in FIELD_ROLES:
|
||||
raise ValidationError("Doctors can only be assigned to an MR")
|
||||
# An MR may only be given doctors from their own headquarters.
|
||||
if mr.headquarters_id != doctor.headquarters_id:
|
||||
if doctor.headquarters_id not in mr.covered_headquarter_ids:
|
||||
raise ValidationError(
|
||||
"MR and doctor belong to different headquarters",
|
||||
{
|
||||
@@ -150,3 +201,13 @@ class DoctorService:
|
||||
)
|
||||
await self.db.commit()
|
||||
return assignment
|
||||
|
||||
async def requests_for(self, actor: User) -> list[Doctor]:
|
||||
return await master_approval.requests_for(self.db, Doctor, actor)
|
||||
|
||||
async def review(
|
||||
self, doctor_id: uuid.UUID, approve: bool, reason: str | None, actor: User, ip: str | None = None
|
||||
) -> Doctor:
|
||||
return await master_approval.review(
|
||||
self.db, Doctor, EntityType.DOCTOR, doctor_id, approve, reason, actor, ip
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user