This commit is contained in:
Shubhankar45
2026-10-27 12:03:31 +00:00
parent 2ed3945b5d
commit 4e5e95775d
104 changed files with 5210 additions and 606 deletions
+37 -2
View File
@@ -22,8 +22,8 @@ class User(Base, UUIDMixin, TimestampMixin):
UniqueConstraint("company_id", "employee_code", name="uq_user_company_empcode"),
# An MR must have a headquarters; nobody else may have one (R4, R8).
CheckConstraint(
"(role = 'MR' AND headquarters_id IS NOT NULL) "
"OR (role <> 'MR' AND headquarters_id IS NULL)",
"(role IN ('MR', 'SFE') AND headquarters_id IS NOT NULL) "
"OR (role NOT IN ('MR', 'SFE') AND headquarters_id IS NULL)",
name="ck_user_mr_requires_hq",
),
)
@@ -45,6 +45,41 @@ class User(Base, UUIDMixin, TimestampMixin):
)
#: Checked on EVERY request, not only at login (SEC-5).
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
#: The one protected owner account. Nobody — not even itself — can edit, deactivate,
#: re-role or delete it through the API; a DB trigger backs that up. It acts as an
#: ADMIN everywhere (role is ADMIN), and is created only by `scripts/create_superadmin.py`.
is_superadmin: Mapped[bool] = mapped_column(
Boolean, default=False, server_default="false", nullable=False
)
failed_login_attempts: Mapped[int] = mapped_column(default=0, nullable=False)
headquarters: Mapped["Headquarters | None"] = relationship() # noqa: F821
#: SFE only — the other headquarters (districts) covered besides the primary one.
extra_headquarters: Mapped[list["UserExtraHeadquarters"]] = relationship(
lazy="selectin", cascade="all, delete-orphan"
)
@property
def extra_headquarter_ids(self) -> list[uuid.UUID]:
return [e.headquarters_id for e in self.extra_headquarters]
@property
def covered_headquarter_ids(self) -> set[uuid.UUID]:
"""Every headquarters this field user works in: the primary one plus the extra ones."""
ids = set(self.extra_headquarter_ids)
if self.headquarters_id:
ids.add(self.headquarters_id)
return ids
class UserExtraHeadquarters(Base):
"""An SFE covers more than one district: each extra headquarters is one row here."""
__tablename__ = "user_extra_headquarters"
user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="CASCADE"), primary_key=True
)
headquarters_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), primary_key=True
)
+168
View File
@@ -0,0 +1,168 @@
"""One person's whole picture for the General Manager and Admin: who they are, where they
work, who they report to, their doctors and chemists, their reports and their company forms."""
import uuid
from typing import Any
from sqlalchemy import func, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.chemists.models import Chemist, ChemistAssignment
from app.common.enums import FIELD_ROLES, ReportType, Role
from app.common.exceptions import NotFoundError
from app.csv_data.config import CSV_LABELS, FORM_ORDER, TABLES
from app.csv_data.models import FormApproval
from app.doctors.models import Doctor, DoctorAssignment
from app.organization.models import AMHeadquarters, Headquarters
from app.reports.models import DailyCallReport
from app.reports.repository import DCRRepository
from app.reports.serializers import to_list_item
from app.users.models import User
def _hq(h: Headquarters, main: bool = False) -> dict[str, Any]:
return {"id": str(h.id), "code": h.code, "name": h.name, "district": h.district, "state": h.state, "main": main}
def _person(u: User) -> dict[str, Any]:
return {"id": str(u.id), "full_name": u.full_name, "email": u.email, "role": u.role.value, "is_active": u.is_active}
async def _report_counts(db: AsyncSession, **where: Any) -> dict[str, dict[str, int]]:
stmt = select(DailyCallReport.report_type, DailyCallReport.status, func.count()).group_by(
DailyCallReport.report_type, DailyCallReport.status
)
if "mr_user_id" in where:
stmt = stmt.where(DailyCallReport.mr_user_id == where["mr_user_id"])
if "hq_ids" in where:
stmt = stmt.where(DailyCallReport.headquarters_id.in_(where["hq_ids"] or [None]))
out: dict[str, dict[str, int]] = {}
for kind, status, n in (await db.execute(stmt)).all():
out.setdefault(str(getattr(kind, "value", kind)), {})[str(getattr(status, "value", status))] = n
return out
async def _forms(db: AsyncSession, user: User) -> list[dict[str, Any]]:
from app.csv_data.approval import APPROVAL_TABLES
from app.csv_data.router import HIDDEN_TABLES, PER_MR_PRODUCT_TABLES
owned = APPROVAL_TABLES | PER_MR_PRODUCT_TABLES
approvals = {
a.table_name: a.status
for a in (await db.execute(select(FormApproval).where(FormApproval.owner_user_id == user.id))).scalars()
}
out = []
for name in FORM_ORDER:
if name in HIDDEN_TABLES:
continue
columns = TABLES[name]
if name in owned:
where, params = "owner_user_id = :v", {"v": user.id}
else:
who = "name" if "name" in columns else "employee_name"
where, params = f"lower(btrim(COALESCE({who}, ''))) = :v", {"v": user.full_name.strip().lower()}
rows = (await db.execute(text(f'SELECT COUNT(*) FROM "{name}" WHERE {where}'), params)).scalar_one()
months: list[str] = []
if "month" in columns:
found = await db.execute(
text(f'SELECT DISTINCT btrim(month) FROM "{name}" WHERE {where} AND btrim(COALESCE(month, \'\')) <> \'\''),
params,
)
months = sorted(m for (m,) in found.all())
out.append(
{
"table": name,
"label": CSV_LABELS[name],
"rows": rows,
"months": months,
"approval_status": approvals.get(name, "draft") if name in APPROVAL_TABLES else None,
}
)
return out
async def user_overview(db: AsyncSession, actor: User, user_id: uuid.UUID) -> dict[str, Any]:
user = await db.get(User, user_id)
if user is None or user.company_id != actor.company_id:
raise NotFoundError("User not found")
repo = DCRRepository(db)
data: dict[str, Any] = {
"user": {
"id": str(user.id), "full_name": user.full_name, "email": user.email,
"employee_code": user.employee_code, "phone": user.phone, "role": user.role.value,
"is_active": user.is_active, "is_superadmin": user.is_superadmin,
},
"headquarters": [], "reporting_managers": [], "doctors": [], "chemists": [],
"reports": {"counts": {}, "recent": []}, "forms": [], "team": [], "own_reports": None,
}
if user.role in FIELD_ROLES:
covered = (
await db.execute(select(Headquarters).where(Headquarters.id.in_(user.covered_headquarter_ids or [None])))
).scalars().all()
data["headquarters"] = sorted((_hq(h, h.id == user.headquarters_id) for h in covered), key=lambda h: not h["main"])
if user.headquarters_id:
managers = (
await db.execute(
select(User)
.join(AMHeadquarters, AMHeadquarters.area_manager_user_id == User.id)
.where(AMHeadquarters.headquarters_id == user.headquarters_id, AMHeadquarters.effective_to.is_(None))
.order_by(User.full_name)
)
).scalars().all()
data["reporting_managers"] = [_person(m) for m in managers]
doctors = await db.execute(
select(Doctor, Headquarters.name)
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
.join(Headquarters, Headquarters.id == Doctor.headquarters_id)
.where(DoctorAssignment.mr_user_id == user.id, DoctorAssignment.effective_to.is_(None))
.order_by(Doctor.name)
)
data["doctors"] = [
{"id": str(d.id), "name": d.name, "speciality": d.speciality, "clinic_address": d.clinic_address,
"headquarters_name": hq, "is_core_doctor": d.is_core_doctor, "is_active": d.is_active}
for d, hq in doctors.all()
]
chemists = await db.execute(
select(Chemist, Headquarters.name)
.join(ChemistAssignment, ChemistAssignment.chemist_id == Chemist.id)
.join(Headquarters, Headquarters.id == Chemist.headquarters_id)
.where(ChemistAssignment.mr_user_id == user.id, ChemistAssignment.effective_to.is_(None))
.order_by(Chemist.name)
)
data["chemists"] = [
{"id": str(c.id), "name": c.name, "shop_address": c.shop_address, "headquarters_name": hq, "is_active": c.is_active}
for c, hq in chemists.all()
]
data["reports"]["counts"] = await _report_counts(db, mr_user_id=user.id)
recent = await repo.list_scoped(mr_user_id=user.id, limit=15)
data["reports"]["recent"] = [to_list_item(r).model_dump(mode="json") for r in recent]
data["forms"] = await _forms(db, user)
elif user.role == Role.AM:
managed = (
await db.execute(
select(Headquarters)
.join(AMHeadquarters, AMHeadquarters.headquarters_id == Headquarters.id)
.where(AMHeadquarters.area_manager_user_id == user.id, AMHeadquarters.effective_to.is_(None))
.order_by(Headquarters.name)
)
).scalars().all()
ids = {h.id for h in managed}
team = (
await db.execute(
select(User).where(User.role.in_(FIELD_ROLES), User.headquarters_id.in_(ids or [None])).order_by(User.full_name)
)
).scalars().all()
counts_by_hq = {
hq_id: n for hq_id, n in (
await db.execute(select(User.headquarters_id, func.count()).where(User.role.in_(FIELD_ROLES), User.is_active.is_(True)).group_by(User.headquarters_id))
).all()
}
data["headquarters"] = [{**_hq(h), "field_staff": counts_by_hq.get(h.id, 0)} for h in managed]
data["team"] = [{**_person(t), "headquarters": next((h.code for h in managed if h.id == t.headquarters_id), None)} for t in team]
data["reports"]["counts"] = await _report_counts(db, hq_ids=ids)
data["reports"]["recent"] = [to_list_item(r).model_dump(mode="json") for r in await repo.list_scoped(hq_ids=ids, limit=15)]
own = await repo.list_scoped(mr_user_id=user.id, report_type=ReportType.SELF, limit=10)
data["own_reports"] = [to_list_item(r).model_dump(mode="json") for r in own]
return data
+11
View File
@@ -6,6 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import client_ip, get_current_user, require_role
from app.common.enums import Role
from app.database.session import get_db
from app.users import overview
from app.users.models import User
from app.users.schemas import MyProfile, UserCreate, UserRead, UserUpdate
from app.users.service import UserService
@@ -20,6 +21,16 @@ async def my_profile(
return await UserService(db).my_profile(current_user)
@router.get("/{user_id}/overview")
async def user_overview(
user_id: uuid.UUID,
current_user: User = Depends(require_role(Role.ADMIN, Role.GM)),
db: AsyncSession = Depends(get_db),
) -> dict:
"""The whole picture of one person, for the General Manager and Admin."""
return await overview.user_overview(db, current_user, user_id)
@router.get("", response_model=list[UserRead])
async def list_users(
role: Role | None = None,
+14 -3
View File
@@ -2,7 +2,7 @@ import uuid
from pydantic import BaseModel, ConfigDict, EmailStr, Field, model_validator
from app.common.enums import Role
from app.common.enums import Role, FIELD_ROLES
class UserCreate(BaseModel):
@@ -14,12 +14,16 @@ class UserCreate(BaseModel):
phone: str | None = Field(default=None, max_length=20)
#: Required for MR, forbidden for every other role (R4/R8).
headquarters_id: uuid.UUID | None = None
#: SFE only: the other districts they cover besides `headquarters_id`.
extra_headquarter_ids: list[uuid.UUID] = []
@model_validator(mode="after")
def check_hq_matches_role(self):
if self.role == Role.MR and self.headquarters_id is None:
if self.extra_headquarter_ids and self.role != Role.SFE:
raise ValueError("extra_headquarter_ids may only be set for an SFE")
if self.role in FIELD_ROLES and self.headquarters_id is None:
raise ValueError("headquarters_id is required for an MR")
if self.role != Role.MR and self.headquarters_id is not None:
if self.role not in FIELD_ROLES and self.headquarters_id is not None:
raise ValueError("headquarters_id may only be set for an MR")
return self
@@ -32,7 +36,12 @@ class UserUpdate(BaseModel):
#: A new password. Signs the user out everywhere and clears a lockout.
password: str | None = Field(default=None, min_length=8, max_length=128)
phone: str | None = Field(default=None, max_length=20)
#: Admin-only. Moving to MR needs `headquarters_id`; leaving MR or AM ends that role's
#: assignments, and the user is signed out so they sign in again with the new role.
role: Role | None = None
headquarters_id: uuid.UUID | None = None
#: SFE only. The full list of extra districts; omit to leave it unchanged.
extra_headquarter_ids: list[uuid.UUID] | None = None
is_active: bool | None = None
@@ -47,6 +56,8 @@ class UserRead(BaseModel):
phone: str | None
headquarters_id: uuid.UUID | None
is_active: bool
is_superadmin: bool = False
extra_headquarter_ids: list[uuid.UUID] = []
class MyProfile(BaseModel):
+95 -11
View File
@@ -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,