Production
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
"""Doctor master data and doctor → MR assignment.
|
||||
|
||||
Master data belongs to a HEADQUARTERS, not to an MR (A2). Assignment is a separate,
|
||||
dated table so that when an MR leaves, the doctor list survives.
|
||||
|
||||
`core_doctor_conversion` was not created as a table (report §13.2): it would store
|
||||
one enum per call, which is a column — `doctor.is_core_doctor` +
|
||||
`doctor_call.conversion_status`.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import Boolean, Date, ForeignKey, Index, String, UniqueConstraint, text
|
||||
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database.base import Base, TimestampMixin, UUIDMixin
|
||||
|
||||
|
||||
class Doctor(Base, UUIDMixin, TimestampMixin):
|
||||
__tablename__ = "doctor"
|
||||
__table_args__ = (
|
||||
# Deduplication guard: two MRs must not create two records for one doctor.
|
||||
UniqueConstraint(
|
||||
"headquarters_id", "name", "clinic_address", name="uq_doctor_hq_name_clinic"
|
||||
),
|
||||
)
|
||||
|
||||
headquarters_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False
|
||||
)
|
||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
speciality: Mapped[str | None] = mapped_column(String(100))
|
||||
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))
|
||||
#: 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)
|
||||
|
||||
assignments: Mapped[list["DoctorAssignment"]] = relationship(back_populates="doctor")
|
||||
|
||||
|
||||
class DoctorAssignment(Base, UUIDMixin, TimestampMixin):
|
||||
__tablename__ = "doctor_assignment"
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"uq_active_doctor_assignment",
|
||||
"doctor_id",
|
||||
unique=True,
|
||||
postgresql_where=text("effective_to IS NULL"),
|
||||
),
|
||||
)
|
||||
|
||||
doctor_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("doctor.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
mr_user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
|
||||
)
|
||||
effective_from: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
effective_to: Mapped[date | None] = mapped_column(Date)
|
||||
|
||||
doctor: Mapped["Doctor"] = relationship(back_populates="assignments")
|
||||
@@ -0,0 +1,64 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
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.service import DoctorService
|
||||
from app.users.models import User
|
||||
|
||||
router = APIRouter(prefix="/doctors", tags=["doctors"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[DoctorRead])
|
||||
async def list_doctors(
|
||||
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||
) -> list[Doctor]:
|
||||
"""S5 — an MR gets only their assigned doctors; managers get their HQ scope."""
|
||||
return await DoctorService(db).list_for(current_user)
|
||||
|
||||
|
||||
@router.post("", response_model=DoctorRead, status_code=status.HTTP_201_CREATED)
|
||||
async def create_doctor(
|
||||
payload: DoctorCreate,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> Doctor:
|
||||
"""Only an Administrator can create a doctor (MR, AM and GM cannot)."""
|
||||
return await DoctorService(db).create(payload, current_user, client_ip(request))
|
||||
|
||||
|
||||
@router.patch("/{doctor_id}", response_model=DoctorRead)
|
||||
async def update_doctor(
|
||||
doctor_id: uuid.UUID,
|
||||
payload: DoctorUpdate,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> Doctor:
|
||||
return await DoctorService(db).update(doctor_id, payload, current_user, client_ip(request))
|
||||
|
||||
|
||||
@router.post("/{doctor_id}/assign", status_code=status.HTTP_201_CREATED)
|
||||
async def assign_doctor(
|
||||
doctor_id: uuid.UUID,
|
||||
payload: AssignToMR,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_role(Role.ADMIN, Role.GM, Role.AM)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""An AM may assign only within their own headquarters — enforced by data scope."""
|
||||
assignment = await DoctorService(db).assign_to_mr(
|
||||
doctor_id, payload.mr_user_id, payload.effective_from, current_user, client_ip(request)
|
||||
)
|
||||
return {
|
||||
"id": assignment.id,
|
||||
"doctor_id": assignment.doctor_id,
|
||||
"mr_user_id": assignment.mr_user_id,
|
||||
"effective_from": assignment.effective_from,
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import uuid
|
||||
from datetime import date
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class DoctorCreate(BaseModel):
|
||||
headquarters_id: uuid.UUID
|
||||
name: str = Field(min_length=2, max_length=200)
|
||||
clinic_address: str = Field(min_length=2, max_length=500)
|
||||
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)
|
||||
is_core_doctor: bool = False
|
||||
|
||||
|
||||
class DoctorUpdate(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=2, max_length=200)
|
||||
clinic_address: str | None = Field(default=None, min_length=2, max_length=500)
|
||||
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)
|
||||
is_core_doctor: bool | None = None
|
||||
is_active: bool | None = None
|
||||
|
||||
|
||||
class DoctorRead(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: uuid.UUID
|
||||
headquarters_id: uuid.UUID
|
||||
name: str
|
||||
clinic_address: str
|
||||
speciality: str | None
|
||||
qualification: str | None
|
||||
contact_number: str | None
|
||||
is_core_doctor: bool
|
||||
is_active: bool
|
||||
|
||||
|
||||
class AssignToMR(BaseModel):
|
||||
mr_user_id: uuid.UUID
|
||||
effective_from: date | None = None
|
||||
@@ -0,0 +1,152 @@
|
||||
import uuid
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
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.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"]
|
||||
|
||||
|
||||
class DoctorService:
|
||||
def __init__(self, db: AsyncSession) -> None:
|
||||
self.db = db
|
||||
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.
|
||||
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
||||
|
||||
doctor = Doctor(**data.model_dump())
|
||||
self.db.add(doctor)
|
||||
try:
|
||||
await self.db.flush()
|
||||
except IntegrityError as exc:
|
||||
await self.db.rollback()
|
||||
raise ConflictError(
|
||||
"A doctor with this name already exists at this clinic in this headquarters",
|
||||
{"cause": "uq_doctor_hq_name_clinic"},
|
||||
) from exc
|
||||
|
||||
await self.audit.log(
|
||||
actor_user_id=actor.id,
|
||||
entity_type=EntityType.DOCTOR,
|
||||
entity_id=doctor.id,
|
||||
action=AuditAction.CREATE,
|
||||
after=snapshot(doctor, _AUDIT_FIELDS),
|
||||
ip_address=ip,
|
||||
)
|
||||
await self.db.commit()
|
||||
return doctor
|
||||
|
||||
async def update(
|
||||
self, doctor_id: uuid.UUID, data: DoctorUpdate, actor: User, ip: str | None = None
|
||||
) -> Doctor:
|
||||
doctor = await self.db.get(Doctor, doctor_id)
|
||||
if doctor is None:
|
||||
raise NotFoundError("Doctor not found")
|
||||
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
||||
|
||||
before = snapshot(doctor, _AUDIT_FIELDS)
|
||||
for field, value in data.model_dump(exclude_unset=True).items():
|
||||
setattr(doctor, field, value)
|
||||
|
||||
await self.audit.log(
|
||||
actor_user_id=actor.id,
|
||||
entity_type=EntityType.DOCTOR,
|
||||
entity_id=doctor.id,
|
||||
action=AuditAction.UPDATE,
|
||||
before=before,
|
||||
after=snapshot(doctor, _AUDIT_FIELDS),
|
||||
ip_address=ip,
|
||||
)
|
||||
await self.db.commit()
|
||||
return doctor
|
||||
|
||||
async def list_for(self, actor: User) -> list[Doctor]:
|
||||
"""An MR sees ONLY doctors currently assigned to them (R5)."""
|
||||
if actor.role == Role.MR:
|
||||
stmt = (
|
||||
select(Doctor)
|
||||
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
|
||||
.where(
|
||||
DoctorAssignment.mr_user_id == actor.id,
|
||||
DoctorAssignment.effective_to.is_(None),
|
||||
Doctor.is_active.is_(True),
|
||||
)
|
||||
.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)
|
||||
if allowed is not None:
|
||||
stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None]))
|
||||
return list((await self.db.execute(stmt)).scalars().all())
|
||||
|
||||
async def assign_to_mr(
|
||||
self,
|
||||
doctor_id: uuid.UUID,
|
||||
mr_user_id: uuid.UUID,
|
||||
effective_from: date | None,
|
||||
actor: User,
|
||||
ip: str | None = None,
|
||||
) -> DoctorAssignment:
|
||||
doctor = await self.db.get(Doctor, doctor_id)
|
||||
if doctor is None:
|
||||
raise NotFoundError("Doctor not found")
|
||||
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
||||
|
||||
mr = await self.db.get(User, mr_user_id)
|
||||
if mr is None:
|
||||
raise NotFoundError("MR not found")
|
||||
if mr.role != Role.MR:
|
||||
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:
|
||||
raise ValidationError(
|
||||
"MR and doctor belong to different headquarters",
|
||||
{
|
||||
"mr_headquarters_id": str(mr.headquarters_id),
|
||||
"doctor_headquarters_id": str(doctor.headquarters_id),
|
||||
},
|
||||
)
|
||||
|
||||
start = effective_from or date.today()
|
||||
existing = (
|
||||
await self.db.execute(
|
||||
select(DoctorAssignment).where(
|
||||
DoctorAssignment.doctor_id == doctor_id,
|
||||
DoctorAssignment.effective_to.is_(None),
|
||||
)
|
||||
)
|
||||
).scalars().all()
|
||||
for row in existing:
|
||||
if row.mr_user_id == mr_user_id:
|
||||
return row
|
||||
row.effective_to = start
|
||||
await self.db.flush()
|
||||
|
||||
assignment = DoctorAssignment(
|
||||
doctor_id=doctor_id, mr_user_id=mr_user_id, effective_from=start
|
||||
)
|
||||
self.db.add(assignment)
|
||||
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(mr_user_id), "effective_from": start.isoformat()},
|
||||
ip_address=ip,
|
||||
)
|
||||
await self.db.commit()
|
||||
return assignment
|
||||
Reference in New Issue
Block a user