Files
Shubhankar45 4e5e95775d --
2026-10-27 12:03:31 +00:00

198 lines
7.6 KiB
Python

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.chemists.models import Chemist, ChemistAssignment
from app.chemists.schemas import ChemistCreate, ChemistUpdate
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
_AUDIT_FIELDS = ["name", "shop_address", "contact_number", "is_active"]
class ChemistService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def create(self, data: ChemistCreate, actor: User, ip: str | None = None) -> Chemist:
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.
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()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A chemist with this name already exists at this address in this headquarters",
{"cause": "uq_chemist_hq_name_shop"},
) from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.CHEMIST,
entity_id=chemist.id,
action=AuditAction.CREATE,
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(
self, chemist_id: uuid.UUID, data: ChemistUpdate, actor: User, ip: str | None = None
) -> Chemist:
chemist = await self.db.get(Chemist, chemist_id)
if chemist is None:
raise NotFoundError("Chemist not found")
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
before = snapshot(chemist, _AUDIT_FIELDS)
for field, value in data.model_dump(exclude_unset=True).items():
setattr(chemist, field, value)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.CHEMIST,
entity_id=chemist.id,
action=AuditAction.UPDATE,
before=before,
after=snapshot(chemist, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return chemist
async def list_for(self, actor: User) -> list[Chemist]:
if actor.role in FIELD_ROLES:
stmt = (
select(Chemist)
.join(ChemistAssignment, ChemistAssignment.chemist_id == Chemist.id)
.where(
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).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())
async def assign_to_mr(
self,
chemist_id: uuid.UUID,
mr_user_id: uuid.UUID,
effective_from: date | None,
actor: User,
ip: str | None = None,
) -> ChemistAssignment:
chemist = await self.db.get(Chemist, chemist_id)
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 not in FIELD_ROLES:
raise ValidationError("Chemists can only be assigned to an MR")
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()
existing = (
await self.db.execute(
select(ChemistAssignment).where(
ChemistAssignment.chemist_id == chemist_id,
ChemistAssignment.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 = ChemistAssignment(
chemist_id=chemist_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.CHEMIST,
entity_id=chemist_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[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
)