"""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