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

141 lines
6.5 KiB
Python

"""Approval workflow for the company forms that carry an Area Manager signature.
draft --request(MR)--> pending --approve(AM)--> approved
pending / approved --any change to the rows--> draft (a signature never covers edited data)
Every MR has their own copy of each form, so approval is per (form, MR). The request goes to the Area
Manager who manages that MR's headquarters, and nobody else can approve it. Only a form that has
rows can be sent, and only a form that has been sent can be approved.
"""
import uuid
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import active_hq_ids_for_am
from app.common.enums import Role, FIELD_ROLES
from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.csv_data.models import FormApproval
from app.organization.models import AMHeadquarters, Headquarters
from app.users.models import User
APPROVAL_TABLES = {"standard_tour_plan", "tour_plan", "fare_chart", "expense_statement"}
async def owners_in_scope(db: AsyncSession, user: User) -> list[User]:
"""The MRs whose forms this user may see: themselves, their headquarters' MRs, or (admin, GM) all."""
stmt = select(User).where(User.role.in_(FIELD_ROLES), User.is_active.is_(True)).order_by(User.full_name)
if user.role in FIELD_ROLES:
stmt = stmt.where(User.id == user.id)
elif user.role == Role.AM:
stmt = stmt.where(User.headquarters_id.in_(await active_hq_ids_for_am(db, user.id)))
elif user.role not in (Role.ADMIN, Role.GM):
return []
return list((await db.execute(stmt)).scalars())
async def assigned_area_manager(db: AsyncSession, owner: User) -> uuid.UUID | None:
if owner.headquarters_id is None:
return None
stmt = select(AMHeadquarters.area_manager_user_id).where(
AMHeadquarters.headquarters_id == owner.headquarters_id, AMHeadquarters.effective_to.is_(None)
)
return (await db.execute(stmt)).scalars().first()
async def assert_owner_in_scope(db: AsyncSession, user: User, owner_id: uuid.UUID) -> User:
"""The MR `owner_id`, if `user` is allowed to see their forms; anything else is refused."""
for owner in await owners_in_scope(db, user):
if owner.id == owner_id:
return owner
if user.role in (Role.ADMIN, Role.GM) or (await db.get(User, owner_id)) is None:
raise NotFoundError("Medical representative not found", {"id": str(owner_id)})
raise ForbiddenError("This form belongs to a medical representative outside your headquarters")
async def get_approval(db: AsyncSession, table_name: str, owner_id: uuid.UUID) -> FormApproval | None:
return await db.get(FormApproval, (table_name, owner_id))
async def _get_or_create(db: AsyncSession, table_name: str, owner_id: uuid.UUID) -> FormApproval:
row = await get_approval(db, table_name, owner_id)
if row is None:
row = FormApproval(table_name=table_name, owner_user_id=owner_id, status="draft")
db.add(row)
await db.flush()
return row
async def list_approvals(db: AsyncSession, user: User) -> list[tuple[FormApproval, User, str | None]]:
"""(approval, MR, headquarters name) for what `user` can see.
An MR always gets all three forms ("draft" until they act); an Area Manager or admin only
gets forms that have been sent, since a draft is nothing for them to act on.
"""
owners = {o.id: o for o in await owners_in_scope(db, user)}
hq_names = {h.id: h.name for h in (await db.execute(select(Headquarters))).scalars()}
existing = {
(r.table_name, r.owner_user_id): r
for r in (await db.execute(select(FormApproval).where(FormApproval.owner_user_id.in_(owners)))).scalars()
}
out: list[tuple[FormApproval, User, str | None]] = []
if user.role in FIELD_ROLES:
for name in sorted(APPROVAL_TABLES):
out.append((existing.get((name, user.id)) or FormApproval(table_name=name, owner_user_id=user.id, status="draft"), user, hq_names.get(user.headquarters_id)))
return out
for (name, owner_id), row in sorted(existing.items()):
if row.status != "draft":
out.append((row, owners[owner_id], hq_names.get(owners[owner_id].headquarters_id)))
return out
async def _row_count(db: AsyncSession, table_name: str, owner_id: uuid.UUID) -> int:
# table_name is only ever one of the fixed APPROVAL_TABLES, never user input.
return (
await db.execute(text(f'SELECT COUNT(*) FROM "{table_name}" WHERE owner_user_id = :o'), {"o": owner_id})
).scalar_one()
async def request_approval(db: AsyncSession, table_name: str, actor: User) -> FormApproval:
if await assigned_area_manager(db, actor) is None:
raise ValidationError("No Area Manager is assigned to your headquarters yet. Ask the administrator to assign one.")
row = await _get_or_create(db, table_name, actor.id)
if row.status == "pending":
return row # already with the Area Manager — a second click changes nothing
if row.status == "approved":
raise ConflictError("This form is already approved. Change a row to send it again.")
if await _row_count(db, table_name, actor.id) == 0:
raise ValidationError("Add at least one row before sending the form for approval")
row.status = "pending"
row.requested_by_user_id = actor.id
await db.commit()
await db.refresh(row)
return row
async def approve(db: AsyncSession, table_name: str, owner_id: uuid.UUID, actor: User) -> FormApproval:
await assert_owner_in_scope(db, actor, owner_id) # only the Area Manager assigned to this MR's headquarters
row = await _get_or_create(db, table_name, owner_id)
if row.status == "approved":
return row # a double click
if row.status != "pending" or await _row_count(db, table_name, owner_id) == 0:
raise ConflictError("Nothing is waiting for approval on this form")
row.status = "approved"
row.approved_by_user_id = actor.id
row.approved_by_name = actor.full_name
await db.commit()
await db.refresh(row)
return row
async def invalidate(db: AsyncSession, table_name: str, owner_id: uuid.UUID | None) -> None:
"""The MR's rows changed: any earlier approval no longer applies. The caller commits."""
if table_name not in APPROVAL_TABLES or owner_id is None:
return
row = await get_approval(db, table_name, owner_id)
if row is not None and row.status != "draft":
row.status = "draft"
row.approved_by_user_id = None
row.approved_by_name = None