Files
celtic-life-science/app/organization/service.py
T
Shubhankar45 8fdd20b29f Production
2026-09-22 06:23:46 +00:00

229 lines
8.1 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 visible_hq_ids
from app.common.enums import AuditAction, EntityType, Role
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
from app.organization.models import AMHeadquarters, Company, Headquarters
from app.organization.schemas import HeadquartersCreate
from app.users.models import User
class OrganizationService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def create_headquarters(
self, data: HeadquartersCreate, actor: User, ip: str | None = None
) -> Headquarters:
if await self.db.get(Company, actor.company_id) is None:
raise NotFoundError("Company not found")
hq = Headquarters(
company_id=actor.company_id,
code=data.code.upper(),
name=data.name,
district=data.district,
state=data.state,
)
self.db.add(hq)
try:
await self.db.flush()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A headquarters with this code already exists", {"code": data.code}
) from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.HEADQUARTERS,
entity_id=hq.id,
action=AuditAction.CREATE,
after={"code": hq.code, "name": hq.name},
ip_address=ip,
)
await self.db.commit()
return hq
async def list_headquarters(self, actor: User) -> list[Headquarters]:
allowed = await visible_hq_ids(self.db, actor)
stmt = select(Headquarters).where(Headquarters.company_id == actor.company_id)
if allowed is not None:
stmt = stmt.where(Headquarters.id.in_(allowed or [None]))
return list((await self.db.execute(stmt)).scalars().all())
async def list_area_manager_mappings(self, actor: User) -> list[AMHeadquarters]:
"""Current (open) Area Manager to headquarters mappings, for display."""
stmt = (
select(AMHeadquarters)
.join(Headquarters, Headquarters.id == AMHeadquarters.headquarters_id)
.where(
Headquarters.company_id == actor.company_id,
AMHeadquarters.effective_to.is_(None),
)
)
return list((await self.db.execute(stmt)).scalars().all())
async def set_area_manager_headquarters(
self,
am_user_id: uuid.UUID,
headquarters_ids: list[uuid.UUID],
effective_from: date | None,
actor: User,
ip: str | None = None,
) -> list[AMHeadquarters]:
"""Make `headquarters_ids` exactly the set of headquarters this AM manages.
Headquarters missing from the list are released, new ones are added. If a new
headquarters already has another AM, that mapping is closed first (one active AM
per headquarters stays true). An AM may manage any number of headquarters.
"""
manager = await self.db.get(User, am_user_id)
if manager is None or manager.company_id != actor.company_id:
raise NotFoundError("User not found")
if manager.role != Role.AM:
raise ValidationError(
"Only a user with the AM role can manage a headquarters",
{"user_role": manager.role.value},
)
wanted = set(headquarters_ids)
if wanted:
found = set(
(
await self.db.execute(
select(Headquarters.id).where(
Headquarters.id.in_(wanted),
Headquarters.company_id == actor.company_id,
)
)
).scalars()
)
if found != wanted:
raise NotFoundError("Headquarters not found")
start = effective_from or date.today()
mine = {
row.headquarters_id: row
for row in (
await self.db.execute(
select(AMHeadquarters).where(
AMHeadquarters.area_manager_user_id == am_user_id,
AMHeadquarters.effective_to.is_(None),
)
)
).scalars()
}
released = set(mine) - wanted
added = wanted - set(mine)
for hq_id in released:
mine[hq_id].effective_to = start
if added:
for row in (
await self.db.execute(
select(AMHeadquarters).where(
AMHeadquarters.headquarters_id.in_(added),
AMHeadquarters.effective_to.is_(None),
)
)
).scalars():
row.effective_to = start
await self.db.flush()
for hq_id in added:
self.db.add(
AMHeadquarters(
area_manager_user_id=am_user_id,
headquarters_id=hq_id,
effective_from=start,
)
)
if added or released:
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.USER,
entity_id=am_user_id,
action=AuditAction.ASSIGN,
before={"headquarters_ids": sorted(str(h) for h in mine)},
after={"headquarters_ids": sorted(str(h) for h in wanted)},
ip_address=ip,
)
await self.db.commit()
return await self.list_area_manager_mappings_for(am_user_id)
async def list_area_manager_mappings_for(self, am_user_id: uuid.UUID) -> list[AMHeadquarters]:
stmt = select(AMHeadquarters).where(
AMHeadquarters.area_manager_user_id == am_user_id,
AMHeadquarters.effective_to.is_(None),
)
return list((await self.db.execute(stmt)).scalars().all())
async def assign_area_manager(
self,
headquarters_id: uuid.UUID,
am_user_id: uuid.UUID,
effective_from: date | None,
actor: User,
ip: str | None = None,
) -> AMHeadquarters:
"""Assign an AM to an HQ, closing any existing active mapping first.
The partial unique index `uq_active_am_per_hq` is the real guarantee that only
one Area Manager is active per headquarters at a time.
"""
hq = await self.db.get(Headquarters, headquarters_id)
if hq is None:
raise NotFoundError("Headquarters not found")
manager = await self.db.get(User, am_user_id)
if manager is None:
raise NotFoundError("User not found")
if manager.role != Role.AM:
raise ValidationError(
"Only a user with the AM role can manage a headquarters",
{"user_role": manager.role.value},
)
start = effective_from or date.today()
existing = (
await self.db.execute(
select(AMHeadquarters).where(
AMHeadquarters.headquarters_id == headquarters_id,
AMHeadquarters.effective_to.is_(None),
)
)
).scalars().all()
for row in existing:
if row.area_manager_user_id == am_user_id:
return row
row.effective_to = start
await self.db.flush()
mapping = AMHeadquarters(
area_manager_user_id=am_user_id,
headquarters_id=headquarters_id,
effective_from=start,
)
self.db.add(mapping)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.HEADQUARTERS,
entity_id=headquarters_id,
action=AuditAction.ASSIGN,
after={"area_manager_user_id": str(am_user_id), "effective_from": start.isoformat()},
ip_address=ip,
)
await self.db.commit()
return mapping