--
This commit is contained in:
@@ -7,6 +7,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
|
||||
|
||||
|
||||
@@ -25,6 +26,22 @@ class Chemist(Base, UUIDMixin, TimestampMixin):
|
||||
shop_address: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
contact_number: Mapped[str | None] = mapped_column(String(20))
|
||||
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["ChemistAssignment"]] = relationship(back_populates="chemist")
|
||||
|
||||
|
||||
+34
-2
@@ -9,7 +9,7 @@ from app.chemists.schemas import ChemistCreate, ChemistRead, ChemistUpdate
|
||||
from app.chemists.service import ChemistService
|
||||
from app.common.enums import Role
|
||||
from app.database.session import get_db
|
||||
from app.doctors.schemas import AssignToMR
|
||||
from app.doctors.schemas import AssignToMR, RejectMaster
|
||||
from app.users.models import User
|
||||
|
||||
router = APIRouter(prefix="/chemists", tags=["chemists"])
|
||||
@@ -26,9 +26,10 @@ async def list_chemists(
|
||||
async def create_chemist(
|
||||
payload: ChemistCreate,
|
||||
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),
|
||||
) -> Chemist:
|
||||
"""An Administrator, or an MR within their own headquarters (AM and GM cannot)."""
|
||||
return await ChemistService(db).create(payload, current_user, client_ip(request))
|
||||
|
||||
|
||||
@@ -60,3 +61,34 @@ async def assign_chemist(
|
||||
"mr_user_id": assignment.mr_user_id,
|
||||
"effective_from": assignment.effective_from,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/requests", response_model=list[ChemistRead])
|
||||
async def list_chemist_requests(
|
||||
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||
) -> list[Chemist]:
|
||||
"""Chemists 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 ChemistService(db).requests_for(current_user)
|
||||
|
||||
|
||||
@router.post("/{chemist_id}/approve", response_model=ChemistRead)
|
||||
async def approve_chemist(
|
||||
chemist_id: uuid.UUID,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> Chemist:
|
||||
"""The Area Manager of its headquarters adds it to the list, assigned to the MR who asked."""
|
||||
return await ChemistService(db).review(chemist_id, True, None, current_user, client_ip(request))
|
||||
|
||||
|
||||
@router.post("/{chemist_id}/reject", response_model=ChemistRead)
|
||||
async def reject_chemist(
|
||||
chemist_id: uuid.UUID,
|
||||
payload: RejectMaster,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> Chemist:
|
||||
return await ChemistService(db).review(chemist_id, False, payload.reason, current_user, client_ip(request))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
@@ -26,3 +27,9 @@ class ChemistRead(BaseModel):
|
||||
shop_address: str
|
||||
contact_number: str | None
|
||||
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
|
||||
|
||||
|
||||
+60
-6
@@ -9,7 +9,8 @@ from app.audit.service import AuditService
|
||||
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
|
||||
from app.chemists.models import Chemist, ChemistAssignment
|
||||
from app.chemists.schemas import ChemistCreate, ChemistUpdate
|
||||
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.users.models import User
|
||||
@@ -25,7 +26,32 @@ class ChemistService:
|
||||
async def create(self, data: ChemistCreate, actor: User, ip: str | None = None) -> Chemist:
|
||||
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
||||
|
||||
chemist = Chemist(**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, Chemist, {k: values[k] for k in ('headquarters_id', 'name', 'shop_address')}
|
||||
)
|
||||
if twin is not None:
|
||||
await master_approval.resubmit(self.db, twin, values, actor, ChemistAssignment, "chemist_id")
|
||||
await self.audit.log(
|
||||
actor_user_id=actor.id,
|
||||
entity_type=EntityType.CHEMIST,
|
||||
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
|
||||
|
||||
chemist = Chemist(
|
||||
**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(chemist)
|
||||
try:
|
||||
await self.db.flush()
|
||||
@@ -44,7 +70,22 @@ class ChemistService:
|
||||
after=snapshot(chemist, _AUDIT_FIELDS),
|
||||
ip_address=ip,
|
||||
)
|
||||
# An MR only sees assigned chemists, so the one they add is assigned to them.
|
||||
if actor.role in FIELD_ROLES:
|
||||
start = date.today()
|
||||
self.db.add(
|
||||
ChemistAssignment(chemist_id=chemist.id, mr_user_id=actor.id, effective_from=start)
|
||||
)
|
||||
await self.audit.log(
|
||||
actor_user_id=actor.id,
|
||||
entity_type=EntityType.CHEMIST,
|
||||
entity_id=chemist.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(chemist)
|
||||
return chemist
|
||||
|
||||
async def update(
|
||||
@@ -72,7 +113,7 @@ class ChemistService:
|
||||
return chemist
|
||||
|
||||
async def list_for(self, actor: User) -> list[Chemist]:
|
||||
if actor.role == Role.MR:
|
||||
if actor.role in FIELD_ROLES:
|
||||
stmt = (
|
||||
select(Chemist)
|
||||
.join(ChemistAssignment, ChemistAssignment.chemist_id == Chemist.id)
|
||||
@@ -80,13 +121,14 @@ class ChemistService:
|
||||
ChemistAssignment.mr_user_id == actor.id,
|
||||
ChemistAssignment.effective_to.is_(None),
|
||||
Chemist.is_active.is_(True),
|
||||
Chemist.approval_status == MasterApproval.APPROVED,
|
||||
)
|
||||
.order_by(Chemist.name)
|
||||
)
|
||||
return list((await self.db.execute(stmt)).scalars().all())
|
||||
|
||||
allowed = await visible_hq_ids(self.db, actor)
|
||||
stmt = select(Chemist).order_by(Chemist.name)
|
||||
stmt = select(Chemist).where(Chemist.approval_status == MasterApproval.APPROVED).order_by(Chemist.name)
|
||||
if allowed is not None:
|
||||
stmt = stmt.where(Chemist.headquarters_id.in_(allowed or [None]))
|
||||
return list((await self.db.execute(stmt)).scalars().all())
|
||||
@@ -103,13 +145,15 @@ class ChemistService:
|
||||
if chemist is None:
|
||||
raise NotFoundError("Chemist not found")
|
||||
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
|
||||
if chemist.approval_status != MasterApproval.APPROVED:
|
||||
raise ValidationError("This chemist 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("Chemists can only be assigned to an MR")
|
||||
if mr.headquarters_id != chemist.headquarters_id:
|
||||
if chemist.headquarters_id not in mr.covered_headquarter_ids:
|
||||
raise ValidationError("MR and chemist belong to different headquarters")
|
||||
|
||||
start = effective_from or date.today()
|
||||
@@ -141,3 +185,13 @@ class ChemistService:
|
||||
)
|
||||
await self.db.commit()
|
||||
return assignment
|
||||
|
||||
async def requests_for(self, actor: User) -> list[Chemist]:
|
||||
return await master_approval.requests_for(self.db, Chemist, actor)
|
||||
|
||||
async def review(
|
||||
self, chemist_id: uuid.UUID, approve: bool, reason: str | None, actor: User, ip: str | None = None
|
||||
) -> Chemist:
|
||||
return await master_approval.review(
|
||||
self.db, Chemist, EntityType.CHEMIST, chemist_id, approve, reason, actor, ip
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user