import uuid from datetime import date from sqlalchemy import select, update from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from app.audit.service import AuditService from app.auth.security import hash_password from app.auth.service import AuthService from app.chemists.models import ChemistAssignment from app.common.enums import AuditAction, EntityType, Role, FIELD_ROLES from app.common.exceptions import ( ConflictError, ForbiddenError, NotFoundError, ValidationError, ) from app.common.utils import snapshot from app.doctors.models import DoctorAssignment from app.organization.models import AMHeadquarters, Headquarters from app.users.models import User, UserExtraHeadquarters from app.users.schemas import MyProfile, UserCreate, UserUpdate _AUDIT_FIELDS = ["email", "full_name", "employee_code", "role", "headquarters_id", "is_active"] class UserService: def __init__(self, db: AsyncSession) -> None: self.db = db self.audit = AuditService(db) async def create(self, data: UserCreate, actor: User, ip: str | None = None) -> User: if data.headquarters_id is not None: hq = await self.db.get(Headquarters, data.headquarters_id) if hq is None: raise NotFoundError("Headquarters not found") if hq.company_id != actor.company_id: raise ValidationError("Headquarters belongs to another company") extras = await self._extra_headquarters(data.extra_headquarter_ids, data.headquarters_id, actor) user = User( extra_headquarters=[UserExtraHeadquarters(headquarters_id=h) for h in extras], company_id=actor.company_id, email=str(data.email).lower(), password_hash=hash_password(data.password), full_name=data.full_name, employee_code=data.employee_code, role=data.role, phone=data.phone, headquarters_id=data.headquarters_id, ) self.db.add(user) try: await self.db.flush() except IntegrityError as exc: await self.db.rollback() raise ConflictError("A user with this email or employee code already exists") from exc await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.USER, entity_id=user.id, action=AuditAction.CREATE, after=snapshot(user, _AUDIT_FIELDS), ip_address=ip, ) await self.db.commit() return user async def _extra_headquarters( self, ids: list[uuid.UUID], primary: uuid.UUID | None, actor: User ) -> list[uuid.UUID]: """The extra districts an SFE covers: each must exist in this company; the primary one and repeats are dropped.""" wanted = list(dict.fromkeys(h for h in ids if h != primary)) for hq_id in wanted: hq = await self.db.get(Headquarters, hq_id) if hq is None or hq.company_id != actor.company_id: raise NotFoundError("Headquarters not found") return wanted async def update( self, user_id: uuid.UUID, data: UserUpdate, actor: User, ip: str | None = None ) -> User: user = await self.db.get(User, user_id) if user is None: raise NotFoundError("User not found") if user.company_id != actor.company_id: raise NotFoundError("User not found") if user.is_superadmin: raise ForbiddenError("The super admin account cannot be edited or deactivated") before = snapshot(user, _AUDIT_FIELDS) deactivating = data.is_active is False and user.is_active changes = data.model_dump(exclude_unset=True) new_password = changes.pop("password", None) if "email" in changes: if changes["email"] is None: raise ValidationError("Email cannot be empty") changes["email"] = str(changes["email"]).lower() if changes.get("role") is None: changes.pop("role", None) old_role = user.role old_hq = user.headquarters_id role_changed = "role" in changes and changes["role"] != old_role if role_changed: if user.id == actor.id: raise ValidationError("You cannot change your own role") # Only an MR has a headquarters; other roles drop it unless told otherwise. if changes["role"] not in FIELD_ROLES: changes.setdefault("headquarters_id", None) if changes.get("headquarters_id") is not None: hq = await self.db.get(Headquarters, changes["headquarters_id"]) if hq is None or hq.company_id != actor.company_id: raise NotFoundError("Headquarters not found") new_extras = changes.pop("extra_headquarter_ids", None) for field, value in changes.items(): setattr(user, field, value) # Only an SFE has extra districts; leaving the SFE role drops them. if user.role != Role.SFE: new_extras = [] if new_extras is not None: wanted = await self._extra_headquarters(new_extras, user.headquarters_id, actor) user.extra_headquarters = [UserExtraHeadquarters(headquarters_id=h) for h in wanted] elif user.role == Role.SFE and "headquarters_id" in changes: # Moving the primary headquarters: it can no longer also be an extra one. user.extra_headquarters = [e for e in user.extra_headquarters if e.headquarters_id != user.headquarters_id] password_reset = new_password is not None if password_reset: user.password_hash = hash_password(new_password) user.failed_login_attempts = 0 # a reset also unlocks the account # An MR must keep a headquarters; nobody else may gain one (DB check mirrors this). if user.role in FIELD_ROLES and user.headquarters_id is None: raise ValidationError("An MR must have a headquarters") if user.role not in FIELD_ROLES and user.headquarters_id is not None: raise ValidationError("Only an MR can have a headquarters") hq_changed = not role_changed and user.role in FIELD_ROLES and user.headquarters_id != old_hq # Changing role, or moving an MR to another headquarters, ends what the old post held. switched_field_role = role_changed and old_role in FIELD_ROLES and user.role in FIELD_ROLES # MR <-> SFE keeps its work released = ( await self._end_role_assignments(user.id, old_role) if (role_changed and not switched_field_role) or hq_changed else {} ) after = snapshot(user, _AUDIT_FIELDS) if password_reset: after["password_reset"] = True # the fact is logged, never the password or its hash if released: after["released"] = released try: await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.USER, entity_id=user.id, action=AuditAction.DEACTIVATE if deactivating else AuditAction.UPDATE, before=before, after=after, ip_address=ip, ) await self.db.commit() except IntegrityError as exc: await self.db.rollback() raise ConflictError("A user with this email or employee code already exists") from exc # SEC-5 — revoke refresh tokens the moment a user is deactivated, or their # credentials or role are changed, so an old session cannot outlive them. if deactivating or password_reset or "email" in changes or role_changed: await AuthService(self.db).logout(user.id) return user async def _end_role_assignments(self, user_id: uuid.UUID, old_role: Role) -> dict[str, int]: """Close what the old role held: an MR's doctors and chemists, an ABM's headquarters.""" today = date.today() if old_role in FIELD_ROLES: targets = [ ("doctors", DoctorAssignment, DoctorAssignment.mr_user_id), ("chemists", ChemistAssignment, ChemistAssignment.mr_user_id), ] elif old_role == Role.ABM: targets = [("headquarters", AMHeadquarters, AMHeadquarters.area_manager_user_id)] else: return {} released = {} for label, model, owner in targets: result = await self.db.execute( update(model) .where(owner == user_id, model.effective_to.is_(None)) .values(effective_to=today) ) if result.rowcount: released[label] = result.rowcount return released async def list_users(self, actor: User, role: Role | None = None) -> list[User]: stmt = select(User).where(User.company_id == actor.company_id) if role is not None: stmt = stmt.where(User.role == role) return list((await self.db.execute(stmt)).scalars().all()) async def my_profile(self, user: User) -> MyProfile: """S4 — includes the reporting Area Business Manager DERIVED through the headquarters.""" hq_code = hq_name = None manager_id = manager_name = None if user.headquarters_id: hq = await self.db.get(Headquarters, user.headquarters_id) if hq: hq_code, hq_name = hq.code, hq.name stmt = ( select(User) .join(AMHeadquarters, AMHeadquarters.area_manager_user_id == User.id) .where( AMHeadquarters.headquarters_id == user.headquarters_id, AMHeadquarters.effective_to.is_(None), ) ) # A headquarters may have several Area Business Managers: name every one. managers = list((await self.db.execute(stmt.order_by(User.full_name))).scalars()) if managers: manager_id = managers[0].id manager_name = ", ".join(m.full_name for m in managers) return MyProfile( id=user.id, full_name=user.full_name, employee_code=user.employee_code, email=user.email, role=user.role, phone=user.phone, headquarters_id=user.headquarters_id, headquarters_code=hq_code, headquarters_name=hq_name, reporting_manager_id=manager_id, reporting_manager_name=manager_name, )