Files
celtic-life-science/app/organization/service.py
Shubhankar45 0d30c58bf0 Server backup 2026-11-07 of uncommitted work in projects/pharma-web-celtic
Snapshot of the working tree on srv1071960 (branch main), taken during
server cleanup. .env files, node_modules, builds, logs and media were excluded.
2026-11-07 05:43:12 +00:00

215 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 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 Business 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 ABM manages.
Headquarters missing from the list are released, new ones are added. Other Area
Managers of the same headquarters keep it: a headquarters may have several.
"""
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.ABM:
raise ValidationError(
"Only an ABM 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
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:
"""Add an Area Business Manager to a headquarters, beside any it already has.
Assigning the same pair twice changes nothing (`uq_active_am_hq_pair`).
"""
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.ABM:
raise ValidationError(
"Only an ABM 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
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