--
This commit is contained in:
+95
-11
@@ -1,17 +1,25 @@
|
||||
import uuid
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import select
|
||||
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.common.enums import AuditAction, EntityType, Role
|
||||
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
||||
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
|
||||
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"]
|
||||
@@ -30,7 +38,9 @@ class UserService:
|
||||
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),
|
||||
@@ -58,6 +68,17 @@ class UserService:
|
||||
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:
|
||||
@@ -67,6 +88,8 @@ class UserService:
|
||||
|
||||
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
|
||||
@@ -77,8 +100,33 @@ class UserService:
|
||||
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:
|
||||
@@ -86,14 +134,25 @@ class UserService:
|
||||
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 == Role.MR and user.headquarters_id is None:
|
||||
if user.role in FIELD_ROLES and user.headquarters_id is None:
|
||||
raise ValidationError("An MR must have a headquarters")
|
||||
if user.role != Role.MR and user.headquarters_id is not None:
|
||||
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,
|
||||
@@ -110,11 +169,34 @@ class UserService:
|
||||
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 are changed, so an old session cannot outlive the old password/email.
|
||||
if deactivating or password_reset or "email" in changes:
|
||||
# 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 AM'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.AM:
|
||||
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:
|
||||
@@ -139,9 +221,11 @@ class UserService:
|
||||
AMHeadquarters.effective_to.is_(None),
|
||||
)
|
||||
)
|
||||
manager = (await self.db.execute(stmt)).scalars().first()
|
||||
if manager:
|
||||
manager_id, manager_name = manager.id, manager.full_name
|
||||
# A headquarters may have several Area 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,
|
||||
|
||||
Reference in New Issue
Block a user