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:
Shubhankar45
2026-11-07 05:43:12 +00:00
parent b001e2d03c
commit 0d30c58bf0
98 changed files with 1878 additions and 573 deletions
+1 -1
View File
@@ -40,7 +40,7 @@ class Doctor(Base, UUIDMixin, TimestampMixin):
#: 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.
#: PENDING until the Area Business 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
)
+27 -10
View File
@@ -17,9 +17,15 @@ 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]:
) -> list[DoctorRead]:
"""S5 — an MR gets only their assigned doctors; managers get their HQ scope."""
return await DoctorService(db).list_for(current_user)
rows = await DoctorService(db).list_for(current_user)
return [
DoctorRead.model_validate(doctor).model_copy(
update={"assigned_mr_name": assigned_mr_name, "assigned_mr_id": mr_id}
)
for doctor, assigned_mr_name, mr_id in rows
]
@router.post("", response_model=DoctorRead, status_code=status.HTTP_201_CREATED)
@@ -29,7 +35,7 @@ async def create_doctor(
current_user: User = Depends(require_role(Role.ADMIN, Role.MR)),
db: AsyncSession = Depends(get_db),
) -> Doctor:
"""An Administrator, or an MR within their own headquarters (AM and GM cannot)."""
"""An Administrator, or an MR within their own headquarters (ABM and AGM cannot)."""
return await DoctorService(db).create(payload, current_user, client_ip(request))
@@ -44,15 +50,26 @@ async def update_doctor(
return await DoctorService(db).update(doctor_id, payload, current_user, client_ip(request))
@router.delete("/{doctor_id}/assign", status_code=status.HTTP_204_NO_CONTENT)
async def unassign_doctor(
doctor_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> None:
"""Administrator only: leave the doctor with no MR."""
await DoctorService(db).unassign(doctor_id, 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)),
current_user: User = Depends(require_role(Role.ADMIN, Role.AGM, Role.ABM)),
db: AsyncSession = Depends(get_db),
):
"""An AM may assign only within their own headquarters — enforced by data scope."""
"""An ABM 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)
)
@@ -68,8 +85,8 @@ async def assign_doctor(
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."""
"""Doctors an MR added that wait for the Area Business Manager: an MR sees their own (with any
rejected and why), an Area Business Manager what waits for them, the administrator and AGM all."""
return await DoctorService(db).requests_for(current_user)
@@ -77,10 +94,10 @@ async def list_doctor_requests(
async def approve_doctor(
doctor_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
current_user: User = Depends(require_role(Role.ABM, 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."""
"""The Area Business 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))
@@ -89,7 +106,7 @@ async def reject_doctor(
doctor_id: uuid.UUID,
payload: RejectMaster,
request: Request,
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Doctor:
return await DoctorService(db).review(doctor_id, False, payload.reason, current_user, client_ip(request))
+4 -1
View File
@@ -24,6 +24,7 @@ class DoctorCreate(BaseModel):
class DoctorUpdate(BaseModel):
headquarters_id: uuid.UUID | None = None
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)
@@ -49,6 +50,8 @@ class DoctorRead(BaseModel):
date_of_birth: date | None
is_core_doctor: bool
is_active: bool
assigned_mr_name: str | None = None
assigned_mr_id: uuid.UUID | None = None
#: PENDING / APPROVED / REJECTED — see app/common/master_approval.py.
approval_status: str
rejection_reason: str | None
@@ -62,6 +65,6 @@ class AssignToMR(BaseModel):
class RejectMaster(BaseModel):
"""Why the Area Manager refused a doctor or chemist an MR added — shown to that MR."""
"""Why the Area Business Manager refused a doctor or chemist an MR added — shown to that MR."""
reason: str = Field(min_length=3, max_length=500)
+50 -22
View File
@@ -1,13 +1,14 @@
import uuid
from datetime import date
from sqlalchemy import select
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
@@ -16,6 +17,7 @@ from app.doctors.schemas import DoctorCreate, DoctorUpdate
from app.users.models import User
_AUDIT_FIELDS = [
"headquarters_id",
"name",
"clinic_address",
"speciality",
@@ -35,7 +37,7 @@ class DoctorService:
await assert_can_view_hq(self.db, actor, data.headquarters_id)
values = data.model_dump()
# Added by an MR: it waits for the Area Manager. One they were refused is sent again.
# 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(
@@ -105,7 +107,11 @@ class DoctorService:
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():
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(
@@ -117,30 +123,52 @@ class DoctorService:
after=snapshot(doctor, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
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[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)."""
if actor.role in FIELD_ROLES:
stmt = (
select(Doctor)
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
.where(
DoctorAssignment.mr_user_id == actor.id,
stmt = (
select(Doctor, User.full_name, User.id)
.outerjoin(
DoctorAssignment,
and_(
DoctorAssignment.doctor_id == Doctor.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())
.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]
allowed = await visible_hq_ids(self.db, actor)
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())
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,
@@ -155,7 +183,7 @@ class DoctorService:
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")
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: