"""Approval of the doctors, chemists and stockists an MR adds. MR adds one --> PENDING --approve(ABM)--> APPROVED (listed, and visitable by that MR) --reject(ABM)---> REJECTED (the MR sees why; adding it again re-sends it) Only APPROVED masters are listed or may be visited. The administrator's own additions are APPROVED at once. The reviewer is the Area Business Manager of the master's headquarters (or the administrator); the Assistant General Manager may look but not act. """ import uuid from datetime import date from typing import Any from sqlalchemy import select 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, MasterApproval, Role, FIELD_ROLES from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError from app.users.models import User def initial_status(actor: User) -> str: return MasterApproval.PENDING if actor.role in FIELD_ROLES else MasterApproval.APPROVED async def rejected_twin(db: AsyncSession, model: Any, match: dict[str, Any]) -> Any | None: """A rejected record with the same identity: adding it again re-sends that one for approval.""" stmt = select(model).where(*(getattr(model, k) == v for k, v in match.items())) found = (await db.execute(stmt)).scalars().first() return found if found is not None and found.approval_status == MasterApproval.REJECTED else None async def resubmit( db: AsyncSession, record: Any, values: dict[str, Any], actor: User, assignment_model: Any | None = None, fk: str | None = None, ) -> None: """Re-send a rejected record with the MR's new details, assigned to that MR (stockists have no per-MR assignment: they belong to the headquarters).""" for field, value in values.items(): setattr(record, field, value) record.approval_status = MasterApproval.PENDING record.requested_by_user_id = actor.id record.rejection_reason = None if assignment_model is None or fk is None: return today = date.today() current = ( await db.execute( select(assignment_model).where( getattr(assignment_model, fk) == record.id, assignment_model.effective_to.is_(None) ) ) ).scalars().all() if not any(a.mr_user_id == actor.id for a in current): for row in current: row.effective_to = today await db.flush() db.add(assignment_model(**{fk: record.id, "mr_user_id": actor.id, "effective_from": today})) async def requests_for(db: AsyncSession, model: Any, actor: User) -> list[Any]: """An MR: what they asked for that is still waiting or was rejected. An Area Business Manager: what waits for them. Administrator and AGM: everything waiting.""" stmt = select(model).order_by(model.created_at.desc()) if actor.role in FIELD_ROLES: return list( ( await db.execute( stmt.where( model.requested_by_user_id == actor.id, model.approval_status.in_([MasterApproval.PENDING, MasterApproval.REJECTED]), ) ) ).scalars() ) stmt = stmt.where(model.approval_status == MasterApproval.PENDING) allowed = await visible_hq_ids(db, actor) if allowed is not None: stmt = stmt.where(model.headquarters_id.in_(allowed or [None])) return list((await db.execute(stmt)).scalars()) async def review( db: AsyncSession, model: Any, entity_type: EntityType, record_id: uuid.UUID, approve: bool, reason: str | None, actor: User, ip: str | None, ) -> Any: record = await db.get(model, record_id) if record is None: raise NotFoundError(f"{entity_type.value.capitalize()} not found") if actor.role not in (Role.ABM, Role.ADMIN): raise ForbiddenError("Only the Area Business Manager approves a new doctor, chemist or stockist") await assert_can_view_hq(db, actor, record.headquarters_id) target = MasterApproval.APPROVED if approve else MasterApproval.REJECTED if record.approval_status == target: return record # a double click if record.approval_status != MasterApproval.PENDING: raise ConflictError("This request has already been decided", {"status": record.approval_status}) record.approval_status = target record.rejection_reason = None if approve else reason await AuditService(db).log( actor_user_id=actor.id, entity_type=entity_type, entity_id=record.id, action=AuditAction.APPROVE if approve else AuditAction.RETURN, before={"approval_status": MasterApproval.PENDING.value}, after={"approval_status": target.value, **({"reason": reason} if reason else {})}, ip_address=ip, ) await db.commit() await db.refresh(record) return record