0d30c58bf0
Snapshot of the working tree on srv1071960 (branch main), taken during server cleanup. .env files, node_modules, builds, logs and media were excluded.
242 lines
9.3 KiB
Python
242 lines
9.3 KiB
Python
import uuid
|
|
from datetime import date
|
|
|
|
from sqlalchemy import and_, 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 import master_approval
|
|
from app.common.master_edit import commit_unique, end_assignments, move_headquarters
|
|
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 = [
|
|
"headquarters_id",
|
|
"name",
|
|
"clinic_address",
|
|
"speciality",
|
|
"date_of_birth",
|
|
"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 belong to a headquarters. An MR may add one only to their own.
|
|
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
|
|
|
values = data.model_dump()
|
|
# Added by an MR: it waits for the Area Business 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()
|
|
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,
|
|
)
|
|
# 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(
|
|
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)
|
|
changes = data.model_dump(exclude_unset=True)
|
|
new_hq = changes.pop("headquarters_id", None)
|
|
if new_hq is not None:
|
|
await move_headquarters(self.db, actor, doctor, new_hq, DoctorAssignment, "doctor_id")
|
|
for field, value in changes.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 commit_unique(self.db, "A doctor with this name already exists at this clinic in this headquarters")
|
|
return doctor
|
|
|
|
async def list_for(self, actor: User) -> list[tuple[Doctor, str | None, uuid.UUID | None]]:
|
|
"""An MR sees ONLY doctors currently assigned to them (R5)."""
|
|
stmt = (
|
|
select(Doctor, User.full_name, User.id)
|
|
.outerjoin(
|
|
DoctorAssignment,
|
|
and_(
|
|
DoctorAssignment.doctor_id == Doctor.id,
|
|
DoctorAssignment.effective_to.is_(None),
|
|
),
|
|
)
|
|
.outerjoin(User, User.id == DoctorAssignment.mr_user_id)
|
|
.where(Doctor.approval_status == MasterApproval.APPROVED)
|
|
.order_by(Doctor.name)
|
|
)
|
|
if actor.role in FIELD_ROLES:
|
|
stmt = stmt.where(
|
|
DoctorAssignment.mr_user_id == actor.id,
|
|
Doctor.is_active.is_(True),
|
|
)
|
|
else:
|
|
allowed = await visible_hq_ids(self.db, actor)
|
|
if allowed is not None:
|
|
stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None]))
|
|
rows = (await self.db.execute(stmt)).all()
|
|
return [(doctor, assigned_mr_name, mr_id) for doctor, assigned_mr_name, mr_id in rows]
|
|
|
|
async def unassign(self, doctor_id: uuid.UUID, actor: User, ip: str | None = None) -> None:
|
|
"""Take the doctor away from its MR, leaving it unassigned."""
|
|
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)
|
|
if await end_assignments(self.db, DoctorAssignment, "doctor_id", doctor_id):
|
|
await self.audit.log(
|
|
actor_user_id=actor.id,
|
|
entity_type=EntityType.DOCTOR,
|
|
entity_id=doctor_id,
|
|
action=AuditAction.UPDATE,
|
|
after={"unassigned": True},
|
|
ip_address=ip,
|
|
)
|
|
await self.db.commit()
|
|
|
|
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)
|
|
if doctor.approval_status != MasterApproval.APPROVED:
|
|
raise ValidationError("This doctor is still waiting for the Area Business Manager's approval")
|
|
|
|
mr = await self.db.get(User, mr_user_id)
|
|
if mr is None:
|
|
raise NotFoundError("MR not found")
|
|
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 doctor.headquarters_id not in mr.covered_headquarter_ids:
|
|
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
|
|
|
|
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
|
|
)
|