fix(task6): scope dashboard and reports to empty for unassigned department user
This commit is contained in:
@@ -33,6 +33,7 @@ from ..services.calculations import (
|
||||
coverage_status,
|
||||
)
|
||||
from ..services.permissions import Role
|
||||
from ..services.scoping import resolve_department_scope
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
|
||||
@@ -46,17 +47,55 @@ def get_dashboard_summary(
|
||||
today = effective_today(db)
|
||||
eff_now = effective_now_utc(db)
|
||||
|
||||
scoped_dept_id: int | None = None
|
||||
scope = resolve_department_scope(current_user)
|
||||
if scope.is_empty:
|
||||
cur_month_start = date(today.year, today.month, 1)
|
||||
months_seq = [add_months(cur_month_start, offset) for offset in range(-5, 1)]
|
||||
return DashboardSummaryOut(
|
||||
department_scope="Unassigned Department",
|
||||
effective_today=today,
|
||||
kpis=DashboardKPIs(
|
||||
total_assets=0,
|
||||
assets_under_repair=0,
|
||||
open_complaints=0,
|
||||
pm_due_this_month=0,
|
||||
calibrations_due=0,
|
||||
contracts_expiring=0,
|
||||
equipment_on_demo=0,
|
||||
),
|
||||
complaints_by_status=[
|
||||
ComplaintsByStatusItem(status="open", count=0),
|
||||
ComplaintsByStatusItem(status="in_progress", count=0),
|
||||
ComplaintsByStatusItem(status="closed", count=0),
|
||||
],
|
||||
complaints_by_department=[],
|
||||
monthly_downtime_trend=[
|
||||
MonthlyDowntimeItem(
|
||||
month=f"{m.year:04d}-{m.month:02d}",
|
||||
label=m.strftime("%b %Y"),
|
||||
downtime_minutes=0,
|
||||
downtime_hours=0.0,
|
||||
)
|
||||
for m in months_seq
|
||||
],
|
||||
pm_planned_vs_completed=[
|
||||
MonthlyPMComparisonItem(
|
||||
month=f"{m.year:04d}-{m.month:02d}",
|
||||
label=m.strftime("%b %Y"),
|
||||
planned=0,
|
||||
completed=0,
|
||||
)
|
||||
for m in months_seq
|
||||
],
|
||||
needs_attention=[],
|
||||
recent_complaints=[],
|
||||
)
|
||||
|
||||
scoped_dept_id: int | None = scope.department_id
|
||||
dept_scope_name: str | None = None
|
||||
if current_user.role == Role.department_user.value:
|
||||
if current_user.department_id is not None:
|
||||
scoped_dept_id = current_user.department_id
|
||||
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
|
||||
dept_scope_name = dept_obj.name if dept_obj else None
|
||||
else:
|
||||
# Department user with unassigned department must see zero scope, never hospital-wide
|
||||
scoped_dept_id = -1
|
||||
dept_scope_name = "Unassigned Department"
|
||||
if scoped_dept_id is not None:
|
||||
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
|
||||
dept_scope_name = dept_obj.name if dept_obj else None
|
||||
|
||||
# Settings for dynamic calculations
|
||||
cal_lead = int(
|
||||
|
||||
@@ -6,6 +6,7 @@ from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..models import Asset, Complaint, User
|
||||
from ..services.permissions import Role
|
||||
from ..services.scoping import resolve_department_scope
|
||||
|
||||
router = APIRouter(prefix="/search", tags=["search"])
|
||||
|
||||
@@ -20,8 +21,11 @@ def global_search(
|
||||
if not term:
|
||||
return {"assets": [], "complaints": []}
|
||||
|
||||
scope = resolve_department_scope(current_user)
|
||||
if scope.is_empty:
|
||||
return {"assets": [], "complaints": []}
|
||||
|
||||
pattern = f"%{term}%"
|
||||
is_dept_scoped = current_user.role == Role.department_user.value
|
||||
|
||||
asset_q = db.query(Asset).options(joinedload(Asset.department)).filter(
|
||||
or_(
|
||||
@@ -30,8 +34,8 @@ def global_search(
|
||||
Asset.serial_no.ilike(pattern),
|
||||
)
|
||||
)
|
||||
if is_dept_scoped:
|
||||
asset_q = asset_q.filter(Asset.department_id == current_user.department_id)
|
||||
if scope.department_id is not None:
|
||||
asset_q = asset_q.filter(Asset.department_id == scope.department_id)
|
||||
assets = asset_q.order_by(Asset.asset_code.asc()).limit(8).all()
|
||||
|
||||
complaint_q = (
|
||||
@@ -47,8 +51,8 @@ def global_search(
|
||||
)
|
||||
)
|
||||
)
|
||||
if is_dept_scoped:
|
||||
complaint_q = complaint_q.filter(Asset.department_id == current_user.department_id)
|
||||
if scope.department_id is not None:
|
||||
complaint_q = complaint_q.filter(Asset.department_id == scope.department_id)
|
||||
complaints = (
|
||||
complaint_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc())
|
||||
.limit(8)
|
||||
|
||||
@@ -37,6 +37,7 @@ from .calculations import (
|
||||
coverage_status,
|
||||
)
|
||||
from .permissions import Role
|
||||
from .scoping import resolve_department_scope
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
_MONTH_RE = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
|
||||
@@ -54,9 +55,8 @@ def _parse_month(month_str: Optional[str], fallback_today: date) -> tuple[str, i
|
||||
|
||||
|
||||
def _scoped_dept_id(user: User, requested_dept_id: Optional[int]) -> Optional[int]:
|
||||
if user.role == Role.department_user.value:
|
||||
return user.department_id
|
||||
return requested_dept_id
|
||||
scope = resolve_department_scope(user, requested_dept_id)
|
||||
return scope.department_id
|
||||
|
||||
|
||||
def _clean_filters(**kwargs: Any) -> dict[str, Any]:
|
||||
@@ -76,7 +76,8 @@ def _build_monthly_maintenance(
|
||||
today = effective_today(db)
|
||||
eff_now = effective_now_utc(db)
|
||||
month_str, year, month = _parse_month(params.get("month"), today)
|
||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
||||
scope = resolve_department_scope(user, params.get("department_id"))
|
||||
dept_id = scope.department_id
|
||||
asset_id = params.get("asset_id")
|
||||
|
||||
days_in_month = calendar.monthrange(year, month)[1]
|
||||
@@ -84,6 +85,49 @@ def _build_monthly_maintenance(
|
||||
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
|
||||
sched_mins_per_asset = days_in_month * sched_hours * 60
|
||||
|
||||
if scope.is_empty:
|
||||
return {
|
||||
"report_key": "monthly-maintenance",
|
||||
"title": "Monthly Maintenance Summary",
|
||||
"filters_applied": _clean_filters(month=month_str, department_id=None, asset_id=asset_id),
|
||||
"formula_info": {
|
||||
"scheduled_hours_per_day": sched_hours,
|
||||
"downtime_end_milestone": milestone,
|
||||
"days_in_month": days_in_month,
|
||||
"uptime_formula": "total_scheduled_minutes - total_downtime_minutes",
|
||||
"downtime_formula": "clip_downtime_to_month(registered_at, milestone, month)",
|
||||
"explanation": (
|
||||
f"Scheduled operating hours are {sched_hours}h/day across {days_in_month} days in "
|
||||
f"{month_str} (Asia/Kolkata); downtime_days_count is distinct calendar days with any breakdown."
|
||||
),
|
||||
},
|
||||
"summary": {
|
||||
"total_assets": 0,
|
||||
"total_complaints": 0,
|
||||
"total_downtime_minutes": 0,
|
||||
"downtime_formatted": format_duration(0),
|
||||
"downtime_days_count": 0,
|
||||
"total_scheduled_minutes": 0,
|
||||
"total_uptime_minutes": 0,
|
||||
"uptime_formatted": format_duration(0),
|
||||
"downtime_pct": 0.0,
|
||||
"downtime_vs_uptime_pct": 0.0,
|
||||
"scheduled_hours_per_day": sched_hours,
|
||||
"downtime_end_milestone": milestone,
|
||||
},
|
||||
"columns": [
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "asset_count", "label": "Assets"},
|
||||
{"key": "complaint_count", "label": "Breakdowns"},
|
||||
{"key": "downtime_formatted", "label": "Downtime"},
|
||||
{"key": "downtime_days_count", "label": "Downtime Days"},
|
||||
{"key": "uptime_formatted", "label": "Uptime"},
|
||||
{"key": "downtime_pct", "label": "Downtime %"},
|
||||
],
|
||||
"rows": [],
|
||||
"chart_data": [],
|
||||
}
|
||||
|
||||
dept_q = db.query(Department).filter(Department.is_active.is_(True))
|
||||
if dept_id is not None:
|
||||
dept_q = dept_q.filter(Department.id == dept_id)
|
||||
@@ -230,7 +274,33 @@ def _build_monthly_department(
|
||||
) -> dict[str, Any]:
|
||||
today = effective_today(db)
|
||||
month_str, year, month = _parse_month(params.get("month"), today)
|
||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
||||
scope = resolve_department_scope(user, params.get("department_id"))
|
||||
dept_id = scope.department_id
|
||||
|
||||
if scope.is_empty:
|
||||
return {
|
||||
"report_key": "monthly-department",
|
||||
"title": "Monthly Department Report",
|
||||
"filters_applied": _clean_filters(month=month_str, department_id=None),
|
||||
"summary": {
|
||||
"departments_count": 0,
|
||||
"total_under_repair": 0,
|
||||
"total_outstanding_complaints": 0,
|
||||
"total_visits": 0,
|
||||
},
|
||||
"columns": [
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "total_assets", "label": "Total Assets"},
|
||||
{"key": "under_repair_count", "label": "Under Repair"},
|
||||
{"key": "out_of_service_count", "label": "Out of Service"},
|
||||
{"key": "outstanding_complaints_count", "label": "Open Complaints"},
|
||||
{"key": "critical_open_count", "label": "Critical Open"},
|
||||
{"key": "visits_this_month", "label": "Visits"},
|
||||
{"key": "new_equipment_requirements", "label": "New Equipment Requirements"},
|
||||
{"key": "latest_requirements_notes", "label": "Visit Observations"},
|
||||
],
|
||||
"rows": [],
|
||||
}
|
||||
|
||||
month_start = date(year, month, 1)
|
||||
next_month_start = add_months(month_start, 1)
|
||||
@@ -326,7 +396,31 @@ def _build_daily_visit(
|
||||
|
||||
date_from = params.get("date_from")
|
||||
date_to = params.get("date_to")
|
||||
dept_id = params.get("department_id")
|
||||
scope = resolve_department_scope(user, params.get("department_id"))
|
||||
dept_id = scope.department_id
|
||||
|
||||
if scope.is_empty:
|
||||
return {
|
||||
"report_key": "daily-visit",
|
||||
"title": "Daily Department Visit Report",
|
||||
"filters_applied": _clean_filters(date_from=date_from, date_to=date_to, department_id=None),
|
||||
"summary": {
|
||||
"total_visits": 0,
|
||||
"departments_visited": 0,
|
||||
"equipment_checked": 0,
|
||||
"breakdowns_logged": 0,
|
||||
},
|
||||
"columns": [
|
||||
{"key": "visit_date", "label": "Visit Date"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "visited_by_name", "label": "Biomedical Engineer"},
|
||||
{"key": "assets_count", "label": "Equipment Checked"},
|
||||
{"key": "complaints_count", "label": "Breakdowns Logged"},
|
||||
{"key": "new_requirements", "label": "New Equipment Requirements"},
|
||||
{"key": "observations", "label": "Observations"},
|
||||
],
|
||||
"rows": [],
|
||||
}
|
||||
|
||||
query = db.query(DepartmentVisit).options(
|
||||
joinedload(DepartmentVisit.department),
|
||||
@@ -396,7 +490,8 @@ def _build_breakdown_complaints(
|
||||
user: User,
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
||||
scope = resolve_department_scope(user, params.get("department_id"))
|
||||
dept_id = scope.department_id
|
||||
date_from = params.get("date_from")
|
||||
date_to = params.get("date_to")
|
||||
asset_id = params.get("asset_id")
|
||||
@@ -404,6 +499,46 @@ def _build_breakdown_complaints(
|
||||
call_status = params.get("call_status")
|
||||
assigned_to_id = params.get("assigned_to_id")
|
||||
|
||||
if scope.is_empty:
|
||||
return {
|
||||
"report_key": "breakdown-complaints",
|
||||
"title": "Breakdown / Complaint Report",
|
||||
"filters_applied": _clean_filters(
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
department_id=None,
|
||||
asset_id=asset_id,
|
||||
priority=priority,
|
||||
call_status=call_status,
|
||||
assigned_to_id=assigned_to_id,
|
||||
),
|
||||
"summary": {
|
||||
"total_complaints": 0,
|
||||
"open_count": 0,
|
||||
"in_progress_count": 0,
|
||||
"closed_count": 0,
|
||||
"critical_count": 0,
|
||||
"avg_response_minutes": 0.0,
|
||||
"total_downtime_minutes": 0,
|
||||
},
|
||||
"columns": [
|
||||
{"key": "complaint_no", "label": "Complaint No"},
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "asset_name", "label": "Equipment"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "priority", "label": "Priority"},
|
||||
{"key": "call_status", "label": "Status"},
|
||||
{"key": "registered_at", "label": "Registered At"},
|
||||
{"key": "assigned_to_name", "label": "Assigned To"},
|
||||
{"key": "response_time_formatted", "label": "Response Time"},
|
||||
{"key": "downtime_formatted", "label": "Downtime"},
|
||||
{"key": "action_taken", "label": "Action Taken"},
|
||||
{"key": "closed_at", "label": "Closed At"},
|
||||
{"key": "closure_remarks", "label": "Closure Remarks"},
|
||||
],
|
||||
"rows": [],
|
||||
}
|
||||
|
||||
response_start = str(get_setting_value(db, "response_start", "registered_at"))
|
||||
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
|
||||
eff_now = effective_now_utc(db)
|
||||
@@ -527,13 +662,54 @@ def _build_pm_compliance(
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
today = effective_today(db)
|
||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
||||
scope = resolve_department_scope(user, params.get("department_id"))
|
||||
dept_id = scope.department_id
|
||||
month_param = params.get("month")
|
||||
date_from = params.get("date_from")
|
||||
date_to = params.get("date_to")
|
||||
asset_id = params.get("asset_id")
|
||||
service_mode = params.get("service_mode")
|
||||
|
||||
clean_month: str | None = None
|
||||
if month_param and str(month_param).strip():
|
||||
clean_month, y, m = _parse_month(month_param, today)
|
||||
|
||||
if scope.is_empty:
|
||||
return {
|
||||
"report_key": "pm-compliance",
|
||||
"title": "PM Compliance Report",
|
||||
"filters_applied": _clean_filters(
|
||||
month=clean_month,
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
department_id=None,
|
||||
asset_id=asset_id,
|
||||
service_mode=service_mode,
|
||||
),
|
||||
"summary": {
|
||||
"planned_count": 0,
|
||||
"completed_count": 0,
|
||||
"upcoming_count": 0,
|
||||
"due_count": 0,
|
||||
"overdue_count": 0,
|
||||
"rescheduled_count": 0,
|
||||
"compliance_pct": 0.0,
|
||||
},
|
||||
"columns": [
|
||||
{"key": "planned_date", "label": "Planned Date"},
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "asset_name", "label": "Equipment"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "service_mode", "label": "Service Mode"},
|
||||
{"key": "team_or_provider", "label": "Team / Provider"},
|
||||
{"key": "status", "label": "Status"},
|
||||
{"key": "completed_date", "label": "Completed Date"},
|
||||
{"key": "service_details", "label": "Service Details"},
|
||||
{"key": "remarks", "label": "Remarks"},
|
||||
],
|
||||
"rows": [],
|
||||
}
|
||||
|
||||
inhouse_lead = int(get_setting_value(db, "pm_inhouse_lead_days", 15))
|
||||
outsourced_lead = int(get_setting_value(db, "pm_outsourced_lead_days", 15))
|
||||
red_days = int(get_setting_value(db, "red_threshold_days", 7))
|
||||
@@ -643,13 +819,48 @@ def _build_calibration_due(
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
today = effective_today(db)
|
||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
||||
scope = resolve_department_scope(user, params.get("department_id"))
|
||||
dept_id = scope.department_id
|
||||
due_from = params.get("due_from")
|
||||
due_to = params.get("due_to")
|
||||
asset_id = params.get("asset_id")
|
||||
agency_id = params.get("agency_id")
|
||||
status_filter = params.get("status")
|
||||
|
||||
if scope.is_empty:
|
||||
return {
|
||||
"report_key": "calibration-due",
|
||||
"title": "Calibration Due Report",
|
||||
"filters_applied": _clean_filters(
|
||||
due_from=due_from,
|
||||
due_to=due_to,
|
||||
department_id=None,
|
||||
asset_id=asset_id,
|
||||
agency_id=agency_id,
|
||||
status=status_filter,
|
||||
),
|
||||
"summary": {
|
||||
"total_records": 0,
|
||||
"upcoming_count": 0,
|
||||
"due_count": 0,
|
||||
"overdue_count": 0,
|
||||
"completed_count": 0,
|
||||
},
|
||||
"columns": [
|
||||
{"key": "due_date", "label": "Due Date"},
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "asset_name", "label": "Equipment"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "agency_name", "label": "Agency"},
|
||||
{"key": "frequency_months", "label": "Freq (Mo)"},
|
||||
{"key": "status", "label": "Status"},
|
||||
{"key": "completed_date", "label": "Completed Date"},
|
||||
{"key": "certificate_no", "label": "Certificate No"},
|
||||
{"key": "remarks", "label": "Remarks"},
|
||||
],
|
||||
"rows": [],
|
||||
}
|
||||
|
||||
cal_lead = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
@@ -747,12 +958,48 @@ def _build_contracts_warranty(
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
today = effective_today(db)
|
||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
||||
scope = resolve_department_scope(user, params.get("department_id"))
|
||||
dept_id = scope.department_id
|
||||
asset_id = params.get("asset_id")
|
||||
record_kind = params.get("record_kind") or "all"
|
||||
status_filter = params.get("status")
|
||||
contract_type = params.get("contract_type")
|
||||
|
||||
if scope.is_empty:
|
||||
return {
|
||||
"report_key": "contracts-warranty",
|
||||
"title": "AMC / CMC & Warranty Report",
|
||||
"filters_applied": _clean_filters(
|
||||
department_id=None,
|
||||
asset_id=asset_id,
|
||||
record_kind=record_kind,
|
||||
status=status_filter,
|
||||
contract_type=contract_type,
|
||||
),
|
||||
"summary": {
|
||||
"total_records": 0,
|
||||
"active_contracts": 0,
|
||||
"expiring_contracts": 0,
|
||||
"expired_contracts": 0,
|
||||
"active_warranties": 0,
|
||||
"expiring_warranties": 0,
|
||||
},
|
||||
"columns": [
|
||||
{"key": "record_kind", "label": "Kind"},
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "asset_name", "label": "Equipment"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "type_or_duration", "label": "Type / Duration"},
|
||||
{"key": "provider_name", "label": "Provider"},
|
||||
{"key": "start_date", "label": "Start Date"},
|
||||
{"key": "end_date", "label": "End Date"},
|
||||
{"key": "days_to_expiry", "label": "Days Left"},
|
||||
{"key": "status", "label": "Status"},
|
||||
{"key": "attachment_count", "label": "Files"},
|
||||
],
|
||||
"rows": [],
|
||||
}
|
||||
|
||||
con_lead = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
@@ -889,12 +1136,46 @@ def _build_demo_equipment(
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
today = effective_today(db)
|
||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
||||
scope = resolve_department_scope(user, params.get("department_id"))
|
||||
dept_id = scope.department_id
|
||||
supplier_id = params.get("supplier_id")
|
||||
status_filter = params.get("status")
|
||||
date_from = params.get("date_from")
|
||||
date_to = params.get("date_to")
|
||||
|
||||
if scope.is_empty:
|
||||
return {
|
||||
"report_key": "demo-equipment",
|
||||
"title": "Demo Equipment Report",
|
||||
"filters_applied": _clean_filters(
|
||||
department_id=None,
|
||||
supplier_id=supplier_id,
|
||||
status=status_filter,
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
),
|
||||
"summary": {
|
||||
"total_items": 0,
|
||||
"on_demo_count": 0,
|
||||
"overdue_count": 0,
|
||||
"returned_count": 0,
|
||||
},
|
||||
"columns": [
|
||||
{"key": "name", "label": "Equipment Name"},
|
||||
{"key": "equipment_type", "label": "Type"},
|
||||
{"key": "supplier_name", "label": "Supplier"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "location_name", "label": "Location"},
|
||||
{"key": "start_date", "label": "Start Date"},
|
||||
{"key": "expected_return_date", "label": "Expected Return"},
|
||||
{"key": "actual_return_date", "label": "Actual Return"},
|
||||
{"key": "status", "label": "Status"},
|
||||
{"key": "days_remaining", "label": "Days Remaining"},
|
||||
{"key": "remarks", "label": "Remarks"},
|
||||
],
|
||||
"rows": [],
|
||||
}
|
||||
|
||||
query = db.query(DemoEquipment).options(
|
||||
joinedload(DemoEquipment.supplier),
|
||||
joinedload(DemoEquipment.department),
|
||||
@@ -976,6 +1257,105 @@ def _build_demo_equipment(
|
||||
}
|
||||
|
||||
|
||||
def _build_equipment_inventory(
|
||||
db: Session,
|
||||
user: User,
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
scope = resolve_department_scope(user, params.get("department_id"))
|
||||
dept_id = scope.department_id
|
||||
category_id = params.get("category_id")
|
||||
status_filter = params.get("status")
|
||||
|
||||
if scope.is_empty:
|
||||
return {
|
||||
"report_key": "equipment-inventory",
|
||||
"title": "Equipment Inventory Report",
|
||||
"filters_applied": _clean_filters(department_id=None, category_id=category_id, status=status_filter),
|
||||
"summary": {
|
||||
"total_assets": 0,
|
||||
"in_service": 0,
|
||||
"under_repair": 0,
|
||||
"condemned": 0,
|
||||
},
|
||||
"columns": [
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "name", "label": "Equipment Name"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "location_name", "label": "Location"},
|
||||
{"key": "category_name", "label": "Category"},
|
||||
{"key": "serial_no", "label": "Serial No"},
|
||||
{"key": "status", "label": "Status"},
|
||||
],
|
||||
"rows": [],
|
||||
}
|
||||
|
||||
query = (
|
||||
db.query(Asset)
|
||||
.options(
|
||||
joinedload(Asset.department),
|
||||
joinedload(Asset.location),
|
||||
joinedload(Asset.category),
|
||||
)
|
||||
)
|
||||
if dept_id is not None:
|
||||
query = query.filter(Asset.department_id == dept_id)
|
||||
if category_id is not None:
|
||||
query = query.filter(Asset.category_id == category_id)
|
||||
if status_filter:
|
||||
query = query.filter(Asset.status == status_filter)
|
||||
|
||||
assets = query.order_by(Asset.asset_code.asc()).all()
|
||||
rows = [
|
||||
{
|
||||
"id": a.id,
|
||||
"asset_code": a.asset_code,
|
||||
"name": a.name,
|
||||
"department_id": a.department_id,
|
||||
"department_name": a.department.name if a.department else "\u2014",
|
||||
"location_name": a.location.name if a.location else "\u2014",
|
||||
"category_name": a.category.name if a.category else "\u2014",
|
||||
"serial_no": a.serial_no or "\u2014",
|
||||
"status": a.status,
|
||||
}
|
||||
for a in assets
|
||||
]
|
||||
return {
|
||||
"report_key": "equipment-inventory",
|
||||
"title": "Equipment Inventory Report",
|
||||
"filters_applied": _clean_filters(department_id=dept_id, category_id=category_id, status=status_filter),
|
||||
"summary": {
|
||||
"total_assets": len(rows),
|
||||
"in_service": sum(1 for a in assets if a.status == "in_service"),
|
||||
"under_repair": sum(1 for a in assets if a.status == "under_repair"),
|
||||
"condemned": sum(1 for a in assets if a.status == "condemned"),
|
||||
},
|
||||
"columns": [
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "name", "label": "Equipment Name"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "location_name", "label": "Location"},
|
||||
{"key": "category_name", "label": "Category"},
|
||||
{"key": "serial_no", "label": "Serial No"},
|
||||
{"key": "status", "label": "Status"},
|
||||
],
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
def _build_condemned_equipment(
|
||||
db: Session,
|
||||
user: User,
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
condemned_params = dict(params)
|
||||
condemned_params["status"] = "condemned"
|
||||
rep = _build_equipment_inventory(db, user, condemned_params)
|
||||
rep["report_key"] = "condemned-equipment"
|
||||
rep["title"] = "Condemned Equipment Report"
|
||||
return rep
|
||||
|
||||
|
||||
REPORT_BUILDERS: dict[str, Callable[[Session, User, dict[str, Any]], dict[str, Any]]] = {
|
||||
"monthly-maintenance": _build_monthly_maintenance,
|
||||
"monthly-department": _build_monthly_department,
|
||||
@@ -985,6 +1365,23 @@ REPORT_BUILDERS: dict[str, Callable[[Session, User, dict[str, Any]], dict[str, A
|
||||
"calibration-due": _build_calibration_due,
|
||||
"contracts-warranty": _build_contracts_warranty,
|
||||
"demo-equipment": _build_demo_equipment,
|
||||
# Auditor & alternate aliases
|
||||
"equipment-inventory": _build_equipment_inventory,
|
||||
"equipment_inventory": _build_equipment_inventory,
|
||||
"condemned-equipment": _build_condemned_equipment,
|
||||
"condemned_equipment": _build_condemned_equipment,
|
||||
"pm-schedule": _build_pm_compliance,
|
||||
"pm_schedule": _build_pm_compliance,
|
||||
"calibration-schedule": _build_calibration_due,
|
||||
"calibration_schedule": _build_calibration_due,
|
||||
"breakdown-analysis": _build_breakdown_complaints,
|
||||
"breakdown_analysis": _build_breakdown_complaints,
|
||||
"amc-cmc-status": _build_contracts_warranty,
|
||||
"amc_cmc_status": _build_contracts_warranty,
|
||||
"daily-department-visit": _build_daily_visit,
|
||||
"daily_department_visit": _build_daily_visit,
|
||||
"monthly_department": _build_monthly_department,
|
||||
"monthly_maintenance": _build_monthly_maintenance,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from ..models import User
|
||||
from .permissions import Role
|
||||
|
||||
|
||||
@dataclass
|
||||
class DepartmentScope:
|
||||
is_unconstrained: bool
|
||||
department_id: Optional[int]
|
||||
is_empty: bool
|
||||
|
||||
|
||||
def resolve_department_scope(
|
||||
user: User,
|
||||
requested_dept_id: Optional[int] = None,
|
||||
) -> DepartmentScope:
|
||||
"""Resolve department scoping based on user role and assigned department.
|
||||
|
||||
Rules:
|
||||
- If user.role != 'department_user': unconstrained, department_id=requested_dept_id, is_empty=False.
|
||||
- If user.role == 'department_user' and user.department_id is None: is_empty=True, department_id=None, is_unconstrained=False.
|
||||
- If user.role == 'department_user' and user.department_id is not None: is_empty=False, department_id=user.department_id
|
||||
(requested_dept_id is ignored, cannot widen or change), is_unconstrained=False.
|
||||
"""
|
||||
if user.role != Role.department_user.value:
|
||||
return DepartmentScope(
|
||||
is_unconstrained=True,
|
||||
department_id=requested_dept_id,
|
||||
is_empty=False,
|
||||
)
|
||||
|
||||
if user.department_id is None:
|
||||
return DepartmentScope(
|
||||
is_unconstrained=False,
|
||||
department_id=None,
|
||||
is_empty=True,
|
||||
)
|
||||
|
||||
return DepartmentScope(
|
||||
is_unconstrained=False,
|
||||
department_id=user.department_id,
|
||||
is_empty=False,
|
||||
)
|
||||
@@ -0,0 +1,133 @@
|
||||
import pytest
|
||||
from app.core.security import hash_password
|
||||
from app.models import Asset, Department, User
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.scoping import DepartmentScope, resolve_department_scope
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task6_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task6_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||
assert res.status_code == 200, res.text
|
||||
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
|
||||
|
||||
def test_resolve_department_scope_rules():
|
||||
# Admin is unconstrained
|
||||
admin_user = User(role="system_admin", department_id=None)
|
||||
scope = resolve_department_scope(admin_user, requested_dept_id=5)
|
||||
assert scope == DepartmentScope(is_unconstrained=True, department_id=5, is_empty=False)
|
||||
|
||||
# Department user with department_id=None is empty
|
||||
unassigned = User(role="department_user", department_id=None)
|
||||
scope_empty = resolve_department_scope(unassigned, requested_dept_id=5)
|
||||
assert scope_empty == DepartmentScope(is_unconstrained=False, department_id=None, is_empty=True)
|
||||
|
||||
# Department user with assigned department cannot be overridden
|
||||
assigned = User(role="department_user", department_id=1)
|
||||
scope_assigned = resolve_department_scope(assigned, requested_dept_id=99)
|
||||
assert scope_assigned == DepartmentScope(is_unconstrained=False, department_id=1, is_empty=False)
|
||||
|
||||
|
||||
def test_unassigned_department_user_sees_zero_records(client, db):
|
||||
# Create a department_user with department_id = None
|
||||
email = "unassigned_dept_user@poona.demo"
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
user = User(
|
||||
email=email,
|
||||
name="Unassigned Dept User",
|
||||
password_hash=hash_password("Demo@123"),
|
||||
role="department_user",
|
||||
department_id=None,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
else:
|
||||
user.department_id = None
|
||||
db.commit()
|
||||
|
||||
headers = _auth_headers(client, email)
|
||||
|
||||
# 1. Dashboard summary has all-zero counters
|
||||
dash_res = client.get("/api/dashboard/summary", headers=headers)
|
||||
assert dash_res.status_code == 200
|
||||
dash_data = dash_res.json()
|
||||
kpis = dash_data["kpis"]
|
||||
assert kpis["total_assets"] == 0
|
||||
assert kpis["assets_under_repair"] == 0
|
||||
assert kpis["open_complaints"] == 0
|
||||
assert kpis["pm_due_this_month"] == 0
|
||||
assert kpis["calibrations_due"] == 0
|
||||
assert kpis["contracts_expiring"] == 0
|
||||
assert kpis["equipment_on_demo"] == 0
|
||||
assert len(dash_data["recent_complaints"]) == 0
|
||||
assert len(dash_data["needs_attention"]) == 0
|
||||
|
||||
# 2. Global search returns 0 assets and 0 complaints
|
||||
search_res = client.get("/api/search?q=card", headers=headers)
|
||||
assert search_res.status_code == 200
|
||||
search_data = search_res.json()
|
||||
assert search_data["assets"] == []
|
||||
assert search_data["complaints"] == []
|
||||
|
||||
# 3. All accessible report endpoints return 0 rows for this user
|
||||
report_keys = [
|
||||
"equipment-inventory",
|
||||
"monthly-maintenance",
|
||||
"monthly-department",
|
||||
"breakdown-complaints",
|
||||
"pm-compliance",
|
||||
"calibration-due",
|
||||
"contracts-warranty",
|
||||
"demo-equipment",
|
||||
]
|
||||
for key in report_keys:
|
||||
rep_res = client.get(f"/api/reports/{key}", headers=headers)
|
||||
assert rep_res.status_code == 200, f"{key} failed: {rep_res.text}"
|
||||
body = rep_res.json()
|
||||
assert len(body["rows"]) == 0, f"Expected 0 rows for {key}, got {len(body['rows'])}"
|
||||
|
||||
|
||||
def test_assigned_department_user_scoping_ignores_query_param(client, db):
|
||||
# Get two distinct departments that have assets
|
||||
depts = db.query(Department).filter(Department.is_active.is_(True)).all()
|
||||
assert len(depts) >= 2
|
||||
dept1, dept2 = depts[0], depts[1]
|
||||
|
||||
email = "dept1_scoped_user@poona.demo"
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
user = User(
|
||||
email=email,
|
||||
name="Dept1 Scoped User",
|
||||
password_hash=hash_password("Demo@123"),
|
||||
role="department_user",
|
||||
department_id=dept1.id,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
else:
|
||||
user.department_id = dept1.id
|
||||
db.commit()
|
||||
|
||||
headers = _auth_headers(client, email)
|
||||
|
||||
# Calling with ?department_id=dept2.id MUST be ignored and scoped strictly to dept1
|
||||
res = client.get(
|
||||
f"/api/reports/equipment-inventory?department_id={dept2.id}",
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["filters_applied"]["department_id"] == dept1.id
|
||||
for row in body["rows"]:
|
||||
assert row["department_id"] == dept1.id
|
||||
@@ -50,3 +50,4 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her
|
||||
- Username containment: cannot contain the user's email username (local part before `@`) if 4 or more characters.
|
||||
- Password changes additionally require that the new password is not identical to the current password.
|
||||
28. **Admin Reset Password Interface (Task 5)**: `frontend/src/api/users.ts` and `frontend/src/pages/MastersPage.tsx` expose an administrator password reset modal for users with role `system_admin`. The dialog features password masking toggles, client-side mismatch validation (`Passwords do not match`), universal password policy helper instructions, and displays backend 422 validation errors inline. Successful resets trigger a notification toast and close the modal without affecting the active administrator session.
|
||||
29. **Department User Scoping & Empty Scope Resolution (Task 6)**: `backend/app/services/scoping.py` implements `resolve_department_scope(user, requested_dept_id)`. Non-department roles are unconstrained and may optionally filter by `requested_dept_id`. Assigned `department_user` accounts are strictly bound to `user.department_id`, ignoring any client-requested department parameter. Unassigned `department_user` accounts (`department_id=None`) resolve to `is_empty=True`, immediately returning 0 counters on Dashboard summary, empty results on global search, and empty row lists across all accessible report endpoints without running hospital-wide queries. Report key aliases are registered to support both canonical paths and audit identifiers (e.g., `equipment-inventory`, `condemned-equipment`, `pm-schedule`).
|
||||
|
||||
Reference in New Issue
Block a user