Files
2026-11-18 18:06:22 +05:30

1766 lines
70 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Pure-Python deterministic metrics engine for AI Reports & Cost Analysis.
All numerical calculations happen here without any language model involvement.
Core functions accept plain dicts/dates and return plain dicts/lists so they can
be unit-tested without a database. Thin loader wrappers fetch SQLAlchemy records
using the same department scoping rules as reports_service.py.
"""
from __future__ import annotations
from datetime import date, datetime, time, timedelta, timezone
import re
from typing import Any, Optional
from sqlalchemy.orm import Session, joinedload
from ..core.time_utils import KOLKATA, add_months, effective_now_utc, effective_today
from ..models import (
Asset,
CalibrationPlan,
CalibrationRecord,
Category,
Complaint,
Contract,
Department,
PMRecord,
PMSchedule,
User,
Warranty,
)
from .calculations import (
compute_response_time_minutes,
compute_schedule_status,
)
from .coverage import get_coverage_map
from .scoping import resolve_department_scope
from .settings_service import get_setting_value
EFFICIENCY_WEIGHTS: dict[str, float] = {
"uptime": 0.50,
"pm_compliance": 0.20,
"response": 0.15,
"repeat_free": 0.15,
}
DEFAULT_AI_SETTINGS: dict[str, Any] = {
"comparison_horizon_years": 5,
"latest_equipment_count": 10,
"default_useful_life_years": 10,
"default_salvage_pct": 5.0,
"default_depreciation_method": "straight_line",
"repeat_failure_count": 3,
"repeat_failure_days": 90,
"replacement_review_ratio": 0.4,
"scheduled_hours_per_day": 24,
"downtime_end_milestone": "restored_at",
"response_start": "registered_at",
"critical_complaint_sla_hours": 4,
"non_critical_complaint_sla_hours": 24,
"pm_inhouse_lead_days": 15,
"pm_outsourced_lead_days": 15,
"calibration_lead_days": 15,
"contract_expiry_alert_days": 30,
"red_threshold_days": 7,
}
def _slug(text: str) -> str:
return re.sub(r"[^A-Za-z0-9]+", "_", (text or "").strip()).strip("_") or "NA"
def format_inr(amount: Optional[float]) -> str:
"""Format a number in Indian Rupees with Indian digit grouping (e.g. ₹12,50,000)."""
if amount is None:
return "—"
neg = amount < 0
rounded = int(round(abs(amount)))
s = str(rounded)
if len(s) <= 3:
grouped = s
else:
last3 = s[-3:]
rest = s[:-3]
parts: list[str] = []
while len(rest) > 2:
parts.insert(0, rest[-2:])
rest = rest[:-2]
if rest:
parts.insert(0, rest)
grouped = ",".join(parts) + "," + last3
return f"-₹{grouped}" if neg else f"₹{grouped}"
def make_metric(
metric_id: str,
label: str,
value: Any,
unit: str = "",
formatted: Optional[str] = None,
) -> dict[str, Any]:
if formatted is None:
if value is None:
formatted = "—"
elif unit == "INR":
formatted = format_inr(float(value))
elif unit == "%":
formatted = f"{float(value):.1f}%"
elif unit == "hours":
formatted = f"{float(value):.1f} hrs"
elif unit == "minutes":
formatted = f"{float(value):.1f} mins"
elif unit == "ratio":
formatted = f"{float(value) * 100:.1f}%"
elif isinstance(value, float):
formatted = f"{value:,.2f}"
else:
formatted = str(value)
return {
"id": metric_id,
"label": label,
"value": value,
"unit": unit,
"formatted": formatted,
}
def _ensure_utc(dt: datetime) -> datetime:
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def _to_date(val: Any) -> Optional[date]:
if val is None:
return None
if isinstance(val, datetime):
return _ensure_utc(val).astimezone(KOLKATA).date()
if isinstance(val, date):
return val
if isinstance(val, str) and val.strip():
return date.fromisoformat(val.strip()[:10])
return None
def _clip_interval_to_period(
start_utc: datetime,
end_utc: datetime,
period_start: date,
period_end: date,
) -> int:
"""Clip a UTC interval to [period_start 00:00 IST, period_end+1 00:00 IST) in whole minutes."""
win_start = KOLKATA.localize(datetime.combine(period_start, time(0, 0, 0)))
win_end = KOLKATA.localize(datetime.combine(period_end + timedelta(days=1), time(0, 0, 0)))
s_loc = _ensure_utc(start_utc).astimezone(KOLKATA)
e_loc = _ensure_utc(end_utc).astimezone(KOLKATA)
clipped_s = max(s_loc, win_start)
clipped_e = min(e_loc, win_end)
if clipped_e <= clipped_s:
return 0
return int((clipped_e - clipped_s).total_seconds() // 60)
def _merged_settings(settings: Optional[dict[str, Any]]) -> dict[str, Any]:
merged = dict(DEFAULT_AI_SETTINGS)
if settings:
merged.update({k: v for k, v in settings.items() if v is not None})
return merged
def _book_value_at_years(
cost: float,
life: int,
salvage_pct: float,
method: str,
years_elapsed: float,
) -> tuple[float, float, float]:
"""Return (book_value, accumulated_depreciation, annual_charge)."""
salvage = cost * (salvage_pct / 100.0)
yrs = max(0.0, years_elapsed)
if method == "written_down":
if cost <= 0:
return (0.0, 0.0, 0.0)
eff_salvage_ratio = (salvage / cost) if salvage > 0 else 0.01
rate = 1.0 - (eff_salvage_ratio ** (1.0 / float(life)))
raw_bv = cost * ((1.0 - rate) ** yrs)
bv = max(salvage, raw_bv)
accum = max(0.0, cost - bv)
annual_charge = 0.0 if yrs >= life else bv * rate
return (bv, accum, annual_charge)
# Default: straight_line
annual = (cost - salvage) / float(life)
raw_bv = cost - annual * yrs
bv = max(salvage, raw_bv)
accum = max(0.0, cost - bv)
annual_charge = 0.0 if yrs >= life else annual
return (bv, accum, annual_charge)
# ---------------------------------------------------------------------------
# (a) Depreciation
# ---------------------------------------------------------------------------
def depreciation(
asset: dict[str, Any],
as_of: date,
settings: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
cfg = _merged_settings(settings)
acq_mode = (asset.get("acquisition_mode") or "purchased").lower()
if acq_mode == "rented":
return {
"applicable": False,
"reason": "rented",
"book_value": None,
"accumulated_depreciation": None,
"annual_charge": None,
"fully_depreciated": False,
"method": None,
"life": None,
"years_elapsed": None,
"salvage_value": None,
"inputs_used": {"acquisition_mode": "rented"},
}
cost = asset.get("purchase_value")
if cost is None or float(cost) <= 0:
return {
"applicable": False,
"reason": "Insufficient data: purchase_value",
"book_value": None,
"accumulated_depreciation": None,
"annual_charge": None,
"fully_depreciated": False,
"method": None,
"life": None,
"years_elapsed": None,
"salvage_value": None,
"inputs_used": {"purchase_value": cost},
}
cost_f = float(cost)
base_date = _to_date(asset.get("installation_date")) or _to_date(asset.get("purchase_date"))
if base_date is None:
return {
"applicable": False,
"reason": "Insufficient data: installation_date or purchase_date",
"book_value": None,
"accumulated_depreciation": None,
"annual_charge": None,
"fully_depreciated": False,
"method": None,
"life": None,
"years_elapsed": None,
"salvage_value": None,
"inputs_used": {"purchase_value": cost_f, "installation_date": None, "purchase_date": None},
}
life = (
asset.get("useful_life_years")
or asset.get("category_default_useful_life_years")
or int(cfg["default_useful_life_years"])
)
life = max(1, int(life))
salv_pct = (
float(asset["salvage_pct"])
if asset.get("salvage_pct") is not None
else float(cfg["default_salvage_pct"])
)
salv_pct = max(0.0, min(50.0, salv_pct))
method = asset.get("depreciation_method") or str(cfg["default_depreciation_method"])
if method not in ("straight_line", "written_down"):
method = "straight_line"
days_elapsed = max(0, (as_of - base_date).days)
years_elapsed = days_elapsed / 365.25
bv, accum, annual_charge = _book_value_at_years(cost_f, life, salv_pct, method, years_elapsed)
salvage_value = cost_f * (salv_pct / 100.0)
fully_dep = years_elapsed >= life
return {
"applicable": True,
"reason": None,
"book_value": round(bv, 2),
"accumulated_depreciation": round(accum, 2),
"annual_charge": round(annual_charge, 2),
"fully_depreciated": fully_dep,
"method": method,
"life": life,
"years_elapsed": round(years_elapsed, 4),
"salvage_pct": salv_pct,
"salvage_value": round(salvage_value, 2),
"inputs_used": {
"purchase_value": cost_f,
"base_date": str(base_date),
"as_of": str(as_of),
"useful_life_years": life,
"salvage_pct": salv_pct,
"depreciation_method": method,
},
}
def depreciation_curve(
asset: dict[str, Any],
as_of: date,
settings: Optional[dict[str, Any]] = None,
) -> list[dict[str, Any]]:
dep = depreciation(asset, as_of, settings)
if not dep["applicable"]:
return []
cost = float(asset["purchase_value"])
life = int(dep["life"])
salv_pct = float(dep["salvage_pct"])
method = str(dep["method"])
base_date = _to_date(asset.get("installation_date")) or _to_date(asset.get("purchase_date"))
base_year = base_date.year if base_date else as_of.year
points: list[dict[str, Any]] = []
for yr in range(0, life + 1):
bv, accum, _ = _book_value_at_years(cost, life, salv_pct, method, float(yr))
points.append(
{
"year_index": yr,
"calendar_year": base_year + yr,
"label": f"Yr {yr} ({base_year + yr})",
"book_value": round(bv, 2),
"accumulated_depreciation": round(accum, 2),
}
)
return points
# ---------------------------------------------------------------------------
# (b) Cost Analysis
# ---------------------------------------------------------------------------
def cost_analysis(
asset: dict[str, Any],
contracts: list[dict[str, Any]],
complaints: list[dict[str, Any]],
pm_schedules: list[dict[str, Any]],
pm_records: list[dict[str, Any]],
as_of: date,
settings: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
cfg = _merged_settings(settings)
review_threshold = float(cfg["replacement_review_ratio"])
acq_mode = (asset.get("acquisition_mode") or "purchased").lower()
pv = float(asset["purchase_value"]) if asset.get("purchase_value") is not None else None
# 1. Contract cost to date (prorated across overlapping contracts up to as_of)
contract_cost = 0.0
for c in contracts:
cval = c.get("contract_value")
s_d = _to_date(c.get("start_date"))
e_d = _to_date(c.get("end_date"))
if cval is None or s_d is None or e_d is None or as_of < s_d:
continue
total_days = max(1, (e_d - s_d).days + 1)
eff_end = min(as_of, e_d)
elapsed_days = max(0, (eff_end - s_d).days + 1)
contract_cost += float(cval) * (elapsed_days / float(total_days))
# 2. Repair and spare cost to date (complaints registered on or before as_of)
repair_and_spare_cost = 0.0
for comp in complaints:
reg_d = _to_date(comp.get("registered_at"))
if reg_d is not None and reg_d > as_of:
continue
repair_and_spare_cost += float(comp.get("repair_cost") or 0.0) + float(
comp.get("spare_cost_estimate") or 0.0
)
# 3. In-house PM cost to date (completed visits * schedule.cost_per_visit)
sched_cost_map: dict[int, float] = {}
for s in pm_schedules:
if s.get("service_mode") == "in_house" and s.get("cost_per_visit") is not None:
sched_cost_map[int(s["id"])] = float(s["cost_per_visit"])
inhouse_pm_cost = 0.0
inhouse_visits_completed = 0
for rec in pm_records:
if rec.get("status") != "completed":
continue
comp_d = _to_date(rec.get("completed_date")) or _to_date(rec.get("planned_date"))
if comp_d is not None and comp_d > as_of:
continue
sid = rec.get("schedule_id")
if sid is not None and int(sid) in sched_cost_map:
inhouse_pm_cost += sched_cost_map[int(sid)]
inhouse_visits_completed += 1
maintenance_cost = contract_cost + repair_and_spare_cost + inhouse_pm_cost
base_date = _to_date(asset.get("installation_date")) or _to_date(asset.get("purchase_date"))
years_used: Optional[float] = None
if base_date is not None:
days_used = max(0, (as_of - base_date).days)
years_used = days_used / 365.25
if acq_mode == "rented":
m_rent = float(asset["monthly_rent"]) if asset.get("monthly_rent") is not None else None
rent_to_date = (m_rent * (years_used * 12.0)) if (m_rent is not None and years_used is not None) else None
lifetime_cost = (rent_to_date + maintenance_cost) if rent_to_date is not None else None
maint_ratio = None
review_flag = False
else:
lifetime_cost = (pv + maintenance_cost) if pv is not None else None
maint_ratio = (maintenance_cost / pv) if (pv is not None and pv > 0) else None
review_flag = bool(maint_ratio is not None and maint_ratio >= review_threshold)
cost_per_year = (
round(lifetime_cost / max(years_used, 1.0 / 12.0), 2)
if (lifetime_cost is not None and years_used is not None and years_used > 0)
else None
)
return {
"purchase_value": round(pv, 2) if pv is not None else None,
"contract_cost_to_date": round(contract_cost, 2),
"repair_and_spare_cost_to_date": round(repair_and_spare_cost, 2),
"inhouse_pm_cost_to_date": round(inhouse_pm_cost, 2),
"inhouse_visits_completed": inhouse_visits_completed,
"maintenance_cost": round(maintenance_cost, 2),
"lifetime_cost": round(lifetime_cost, 2) if lifetime_cost is not None else None,
"maintenance_ratio": round(maint_ratio, 4) if maint_ratio is not None else None,
"cost_per_year_of_use": cost_per_year,
"review_flag": review_flag,
"review_threshold": review_threshold,
}
# ---------------------------------------------------------------------------
# (c) Scenario Comparison (In-House vs Outsourced vs Rent)
# ---------------------------------------------------------------------------
def _latest_contract_for_comparison(contracts: list[dict[str, Any]]) -> Optional[dict[str, Any]]:
non_sup = [c for c in contracts if not c.get("is_superseded")]
pool = non_sup if non_sup else list(contracts)
if not pool:
return None
pool.sort(
key=lambda c: (
_to_date(c.get("end_date")) or date.min,
int(c.get("id") or 0),
),
reverse=True,
)
return pool[0]
def scenario_comparison(
asset: dict[str, Any],
contracts: list[dict[str, Any]],
complaints: list[dict[str, Any]],
pm_schedules: list[dict[str, Any]],
horizon_years: Optional[int] = None,
as_of: Optional[date] = None,
settings: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
cfg = _merged_settings(settings)
horizon = int(horizon_years if horizon_years is not None else cfg["comparison_horizon_years"])
ref_date = as_of or date.today()
acq_mode = (asset.get("acquisition_mode") or "purchased").lower()
pv = float(asset["purchase_value"]) if asset.get("purchase_value") is not None else None
monthly_rent = float(asset["monthly_rent"]) if asset.get("monthly_rent") is not None else None
life = (
asset.get("useful_life_years")
or asset.get("category_default_useful_life_years")
or int(cfg["default_useful_life_years"])
)
life = max(1, int(life))
salv_pct = (
float(asset["salvage_pct"])
if asset.get("salvage_pct") is not None
else float(cfg["default_salvage_pct"])
)
method = asset.get("depreciation_method") or str(cfg["default_depreciation_method"])
if method not in ("straight_line", "written_down"):
method = "straight_line"
book_value_at_horizon: Optional[float] = None
dep_loss_over_horizon: Optional[float] = None
if pv is not None and pv > 0:
bv_h, _, _ = _book_value_at_years(pv, life, salv_pct, method, float(horizon))
book_value_at_horizon = round(bv_h, 2)
dep_loss_over_horizon = round(pv - bv_h, 2)
# Annual breakdown cost over last 12 months relative to ref_date
cutoff_12m = ref_date - timedelta(days=365)
annual_repair_only = 0.0
annual_spare_only = 0.0
for comp in complaints:
reg_d = _to_date(comp.get("registered_at"))
if reg_d is not None and (reg_d < cutoff_12m or reg_d > ref_date):
continue
annual_repair_only += float(comp.get("repair_cost") or 0.0)
annual_spare_only += float(comp.get("spare_cost_estimate") or 0.0)
annual_breakdown_full = annual_repair_only + annual_spare_only
# Active in-house PM schedule
inhouse_scheds = [
s for s in pm_schedules if s.get("service_mode") == "in_house" and s.get("is_active", True)
]
outsourced_scheds = [
s for s in pm_schedules if s.get("service_mode") == "outsourced" and s.get("is_active", True)
]
inhouse_sched = inhouse_scheds[0] if inhouse_scheds else None
annual_inhouse_cost: Optional[float] = None
if inhouse_sched and inhouse_sched.get("cost_per_visit") is not None:
freq_m = max(1, int(inhouse_sched.get("frequency_months") or 6))
visits_per_year = 12.0 / float(freq_m)
annual_inhouse_cost = float(inhouse_sched["cost_per_visit"]) * visits_per_year
# Latest contract
latest_contract = _latest_contract_for_comparison(contracts)
annual_contract_cost: Optional[float] = None
contract_type: Optional[str] = None
if latest_contract and latest_contract.get("contract_value") is not None:
contract_type = (latest_contract.get("contract_type") or "").upper()
s_d = _to_date(latest_contract.get("start_date"))
e_d = _to_date(latest_contract.get("end_date"))
if s_d is not None and e_d is not None and e_d >= s_d:
days = (e_d - s_d).days + 1
contract_years = 1.0 if 364 <= days <= 366 else max(days / 365.25, 1.0 / 365.25)
annual_contract_cost = float(latest_contract["contract_value"]) / contract_years
# Scenario A: Buy + in-house maintenance
if pv is None or pv <= 0:
scen_a = {
"key": "in_house",
"label": "Buy + In-House Maintenance",
"available": False,
"total_cost": None,
"insufficient_reason": "Insufficient data: purchase_value",
"breakdown": None,
}
elif annual_inhouse_cost is None:
scen_a = {
"key": "in_house",
"label": "Buy + In-House Maintenance",
"available": False,
"total_cost": None,
"insufficient_reason": "Insufficient data: in-house PM cost_per_visit",
"breakdown": None,
}
else:
total_a = dep_loss_over_horizon + horizon * annual_inhouse_cost + horizon * annual_breakdown_full
scen_a = {
"key": "in_house",
"label": "Buy + In-House Maintenance",
"available": True,
"total_cost": round(total_a, 2),
"insufficient_reason": None,
"breakdown": {
"depreciation_loss": round(dep_loss_over_horizon, 2),
"pm_total": round(horizon * annual_inhouse_cost, 2),
"breakdown_total": round(horizon * annual_breakdown_full, 2),
},
}
# Scenario B: Buy + outsourced contract (AMC/CMC)
# CMC excludes spare_cost_estimate because CMC covers parts; repair_cost is kept.
if pv is None or pv <= 0:
scen_b = {
"key": "outsourced",
"label": "Buy + Outsourced Contract (AMC/CMC)",
"available": False,
"total_cost": None,
"insufficient_reason": "Insufficient data: purchase_value",
"breakdown": None,
}
elif annual_contract_cost is None:
scen_b = {
"key": "outsourced",
"label": "Buy + Outsourced Contract (AMC/CMC)",
"available": False,
"total_cost": None,
"insufficient_reason": "Insufficient data: contract_value",
"breakdown": None,
}
else:
b_annual_breakdown = (
annual_repair_only if contract_type == "CMC" else annual_breakdown_full
)
total_b = dep_loss_over_horizon + horizon * annual_contract_cost + horizon * b_annual_breakdown
scen_b = {
"key": "outsourced",
"label": f"Buy + Outsourced ({contract_type or 'AMC/CMC'})",
"available": True,
"total_cost": round(total_b, 2),
"insufficient_reason": None,
"breakdown": {
"depreciation_loss": round(dep_loss_over_horizon, 2),
"contract_total": round(horizon * annual_contract_cost, 2),
"breakdown_total": round(horizon * b_annual_breakdown, 2),
"cmc_spares_excluded": contract_type == "CMC",
},
}
# Scenario C: Rent
if monthly_rent is None or monthly_rent <= 0:
scen_c = {
"key": "rent",
"label": "Rent",
"available": False,
"total_cost": None,
"insufficient_reason": "Insufficient data: monthly_rent",
"breakdown": None,
}
else:
total_c = monthly_rent * 12.0 * horizon
scen_c = {
"key": "rent",
"label": "Rent",
"available": True,
"total_cost": round(total_c, 2),
"insufficient_reason": None,
"breakdown": {
"monthly_rent": round(monthly_rent, 2),
"months": 12 * horizon,
},
}
scenarios = {"in_house": scen_a, "outsourced": scen_b, "rent": scen_c}
available = [s for s in (scen_a, scen_b, scen_c) if s["available"] and s["total_cost"] is not None]
available.sort(key=lambda s: s["total_cost"])
lowest = available[0] if len(available) >= 1 else None
second_lowest = available[1] if len(available) >= 2 else None
diff_to_next = (
round(second_lowest["total_cost"] - lowest["total_cost"], 2)
if (lowest and second_lowest)
else None
)
if acq_mode == "rented":
current_setup: Optional[str] = "rent"
elif inhouse_sched is not None:
current_setup = "in_house"
elif outsourced_scheds or latest_contract is not None:
current_setup = "outsourced"
else:
current_setup = None
return {
"horizon_years": horizon,
"scenarios": scenarios,
"lowest_scenario": lowest["key"] if lowest else None,
"lowest_scenario_label": lowest["label"] if lowest else None,
"lowest_cost": lowest["total_cost"] if lowest else None,
"next_scenario": second_lowest["key"] if second_lowest else None,
"savings_vs_next": diff_to_next,
"current_setup": current_setup,
"inputs_used": {
"purchase_value": pv,
"book_value_at_horizon": book_value_at_horizon,
"annual_inhouse_cost": round(annual_inhouse_cost, 2) if annual_inhouse_cost is not None else None,
"annual_contract_cost": round(annual_contract_cost, 2) if annual_contract_cost is not None else None,
"contract_type": contract_type,
"annual_breakdown_cost": round(annual_breakdown_full, 2),
"annual_repair_cost": round(annual_repair_only, 2),
"annual_spare_cost": round(annual_spare_only, 2),
"monthly_rent": monthly_rent,
"useful_life_years": life,
"salvage_pct": salv_pct,
"depreciation_method": method,
},
}
# ---------------------------------------------------------------------------
# (d) Breakdown Frequency
# ---------------------------------------------------------------------------
def breakdown_frequency(
assets: list[dict[str, Any]],
complaints: list[dict[str, Any]],
period_start: date,
period_end: date,
effective_today_date: date,
settings: Optional[dict[str, Any]] = None,
now_utc: Optional[datetime] = None,
) -> dict[str, Any]:
cfg = _merged_settings(settings)
repeat_cnt = int(cfg["repeat_failure_count"])
repeat_days = int(cfg["repeat_failure_days"])
sched_hours_day = int(cfg["scheduled_hours_per_day"])
milestone = str(cfg["downtime_end_milestone"])
eff_now = now_utc or KOLKATA.localize(datetime.combine(effective_today_date, time(23, 59, 59))).astimezone(timezone.utc)
period_days = max(1, (period_end - period_start).days + 1)
sched_hours_per_asset = period_days * sched_hours_day
asset_by_id = {int(a["id"]): a for a in assets}
repeat_cutoff = effective_today_date - timedelta(days=repeat_days)
period_complaints_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_by_id}
repeat_window_by_asset: dict[int, int] = {aid: 0 for aid in asset_by_id}
monthly_counts: dict[str, int] = {}
# Seed every month in [period_start, period_end] with 0 so chart has continuous timeline
cur_m = date(period_start.year, period_start.month, 1)
end_m = date(period_end.year, period_end.month, 1)
while cur_m <= end_m:
monthly_counts[cur_m.strftime("%Y-%m")] = 0
cur_m = add_months(cur_m, 1)
for comp in complaints:
aid = int(comp["asset_id"])
if aid not in asset_by_id:
continue
reg_d = _to_date(comp.get("registered_at"))
if reg_d is None:
continue
if repeat_cutoff <= reg_d <= effective_today_date:
repeat_window_by_asset[aid] = repeat_window_by_asset.get(aid, 0) + 1
if period_start <= reg_d <= period_end:
period_complaints_by_asset[aid].append(comp)
ym = reg_d.strftime("%Y-%m")
monthly_counts[ym] = monthly_counts.get(ym, 0) + 1
per_asset: list[dict[str, Any]] = []
dept_agg: dict[str, dict[str, Any]] = {}
cat_agg: dict[str, dict[str, Any]] = {}
for aid, a in asset_by_id.items():
cmps = period_complaints_by_asset.get(aid, [])
dt_list: list[int] = []
for comp in cmps:
reg_dt = comp.get("registered_at")
if isinstance(reg_dt, str):
reg_dt = datetime.fromisoformat(reg_dt)
end_dt = comp.get(milestone) or eff_now
if isinstance(end_dt, str):
end_dt = datetime.fromisoformat(end_dt)
if isinstance(reg_dt, datetime) and isinstance(end_dt, datetime):
mins = max(0, int((_ensure_utc(end_dt) - _ensure_utc(reg_dt)).total_seconds() // 60))
dt_list.append(mins)
avg_dt_mins = round(sum(dt_list) / len(dt_list), 1) if dt_list else 0.0
rw_count = repeat_window_by_asset.get(aid, 0)
is_repeat = rw_count >= repeat_cnt
dept_name = a.get("department_name") or "Unassigned"
cat_name = a.get("category_name") or "Uncategorized"
per_asset.append(
{
"asset_id": aid,
"asset_code": a["asset_code"],
"asset_name": a["name"],
"department_name": dept_name,
"category_name": cat_name,
"breakdown_count": len(cmps),
"avg_downtime_minutes": avg_dt_mins,
"avg_downtime_hours": round(avg_dt_mins / 60.0, 2),
"repeat_window_count": rw_count,
"repeat_failure": is_repeat,
}
)
d_bucket = dept_agg.setdefault(
dept_name,
{"group": dept_name, "group_type": "department", "breakdowns": 0, "assets_in_scope": 0},
)
d_bucket["assets_in_scope"] += 1
d_bucket["breakdowns"] += len(cmps)
c_bucket = cat_agg.setdefault(
cat_name,
{"group": cat_name, "group_type": "category", "breakdowns": 0, "assets_in_scope": 0},
)
c_bucket["assets_in_scope"] += 1
c_bucket["breakdowns"] += len(cmps)
def _finalize_group(bucket: dict[str, Any]) -> dict[str, Any]:
n_assets = bucket["assets_in_scope"]
total_b = bucket["breakdowns"]
total_sched_h = n_assets * sched_hours_per_asset
avg_per_eq = round(total_b / n_assets, 2) if n_assets > 0 else 0.0
per_1000 = round((total_b / total_sched_h) * 1000.0, 3) if total_sched_h > 0 else 0.0
return {
**bucket,
"avg_breakdowns_per_equipment": avg_per_eq,
"breakdowns_per_1000_hours": per_1000,
}
by_department = sorted(
[_finalize_group(b) for b in dept_agg.values()],
key=lambda r: (-r["breakdowns"], r["group"]),
)
by_category = sorted(
[_finalize_group(b) for b in cat_agg.values()],
key=lambda r: (-r["breakdowns"], r["group"]),
)
top_10_assets = sorted(
per_asset,
key=lambda r: (-r["breakdown_count"], -r["repeat_window_count"], r["asset_code"]),
)[:10]
monthly_trend = [
{
"month": ym,
"label": datetime.strptime(ym, "%Y-%m").strftime("%b %Y"),
"breakdowns": cnt,
}
for ym, cnt in sorted(monthly_counts.items())
]
total_breakdowns = sum(r["breakdown_count"] for r in per_asset)
assets_count = len(per_asset)
overall_avg_per_eq = round(total_breakdowns / assets_count, 2) if assets_count > 0 else 0.0
repeat_failure_assets = [r for r in per_asset if r["repeat_failure"]]
evidence: list[dict[str, Any]] = [
make_metric("m_bf_total_breakdowns", "Total Breakdowns in Period", total_breakdowns, "count"),
make_metric("m_bf_assets_in_scope", "Assets in Scope", assets_count, "count"),
make_metric(
"m_bf_avg_per_equipment",
"Average Breakdowns per Equipment",
overall_avg_per_eq,
"breakdowns/asset",
f"{overall_avg_per_eq:.2f}",
),
make_metric(
"m_bf_repeat_failure_assets",
f"Repeat-Failure Assets (>={repeat_cnt} in {repeat_days}d)",
len(repeat_failure_assets),
"count",
),
]
for row in top_10_assets:
if row["breakdown_count"] > 0 or row["repeat_failure"]:
slug = _slug(row["asset_code"])
evidence.append(
make_metric(
f"m_bf_count_{slug}",
f"Breakdowns ({row['asset_code']})",
row["breakdown_count"],
"count",
)
)
evidence.append(
make_metric(
f"m_bf_repeat_window_{slug}",
f"Breakdowns in Last {repeat_days}d ({row['asset_code']})",
row["repeat_window_count"],
"count",
)
)
return {
"summary": {
"total_breakdowns": total_breakdowns,
"assets_in_scope": assets_count,
"avg_breakdowns_per_equipment": overall_avg_per_eq,
"repeat_failure_count": len(repeat_failure_assets),
"repeat_threshold": repeat_cnt,
"repeat_window_days": repeat_days,
},
"per_asset": per_asset,
"by_department": by_department,
"by_category": by_category,
"top_10_assets": top_10_assets,
"monthly_trend": monthly_trend,
"evidence": evidence,
}
# ---------------------------------------------------------------------------
# (e) Efficiency
# ---------------------------------------------------------------------------
def _compute_response_score(response_hours: float, target_sla_hours: float) -> float:
if target_sla_hours <= 0:
return 100.0
if response_hours <= target_sla_hours:
return 100.0
if response_hours >= 4.0 * target_sla_hours:
return 0.0
return 100.0 * (4.0 * target_sla_hours - response_hours) / (3.0 * target_sla_hours)
def efficiency(
assets: list[dict[str, Any]],
complaints: list[dict[str, Any]],
pm_records: list[dict[str, Any]],
period_start: date,
period_end: date,
effective_today_date: date,
settings: Optional[dict[str, Any]] = None,
now_utc: Optional[datetime] = None,
) -> dict[str, Any]:
cfg = _merged_settings(settings)
sched_hours_day = int(cfg["scheduled_hours_per_day"])
milestone = str(cfg["downtime_end_milestone"])
response_start = str(cfg["response_start"])
crit_sla = float(cfg["critical_complaint_sla_hours"])
non_crit_sla = float(cfg["non_critical_complaint_sla_hours"])
repeat_cnt = int(cfg["repeat_failure_count"])
repeat_days = int(cfg["repeat_failure_days"])
eff_now = now_utc or KOLKATA.localize(datetime.combine(effective_today_date, time(23, 59, 59))).astimezone(timezone.utc)
period_days = max(1, (period_end - period_start).days + 1)
sched_mins_per_asset = period_days * sched_hours_day * 60
sched_hours_per_asset = period_days * sched_hours_day
# Exclude condemned assets from operational efficiency (matching Monthly Maintenance report)
active_assets = [a for a in assets if a.get("status") != "condemned"]
asset_ids = {int(a["id"]) for a in active_assets}
repeat_cutoff = effective_today_date - timedelta(days=repeat_days)
complaints_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids}
repeat_window_by_asset: dict[int, int] = {aid: 0 for aid in asset_ids}
for comp in complaints:
aid = int(comp["asset_id"])
if aid not in asset_ids:
continue
complaints_by_asset[aid].append(comp)
reg_d = _to_date(comp.get("registered_at"))
if reg_d is not None and repeat_cutoff <= reg_d <= effective_today_date:
repeat_window_by_asset[aid] = repeat_window_by_asset.get(aid, 0) + 1
pm_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids}
for rec in pm_records:
aid = int(rec["asset_id"])
if aid not in asset_ids:
continue
p_d = _to_date(rec.get("planned_date"))
if p_d is not None and period_start <= p_d <= period_end:
pm_by_asset[aid].append(rec)
per_asset: list[dict[str, Any]] = []
all_mttr: list[float] = []
all_resp_mins: list[int] = []
total_pm_due = 0
total_pm_on_time = 0
for a in active_assets:
aid = int(a["id"])
cmps = complaints_by_asset.get(aid, [])
downtime_mins = 0
period_breakdown_count = 0
mttr_vals: list[float] = []
resp_mins_vals: list[int] = []
resp_scores: list[float] = []
for comp in cmps:
reg_dt = comp.get("registered_at")
if isinstance(reg_dt, str):
reg_dt = datetime.fromisoformat(reg_dt)
if not isinstance(reg_dt, datetime):
continue
end_raw = comp.get(milestone)
if isinstance(end_raw, str):
end_raw = datetime.fromisoformat(end_raw)
end_dt = end_raw if isinstance(end_raw, datetime) else eff_now
clipped = _clip_interval_to_period(reg_dt, end_dt, period_start, period_end)
downtime_mins += clipped
reg_d = _to_date(reg_dt)
if reg_d is not None and period_start <= reg_d <= period_end:
period_breakdown_count += 1
# MTTR: restored_at or closed_at minus registered_at
res_raw = comp.get("restored_at") or comp.get("closed_at")
if isinstance(res_raw, str):
res_raw = datetime.fromisoformat(res_raw)
if isinstance(res_raw, datetime):
mttr_h = max(0.0, (_ensure_utc(res_raw) - _ensure_utc(reg_dt)).total_seconds() / 3600.0)
mttr_vals.append(mttr_h)
all_mttr.append(mttr_h)
# Response time & SLA score
recv_raw = comp.get("received_at")
att_raw = comp.get("attended_at")
if isinstance(recv_raw, str):
recv_raw = datetime.fromisoformat(recv_raw)
if isinstance(att_raw, str):
att_raw = datetime.fromisoformat(att_raw)
rt_min = compute_response_time_minutes(reg_dt, recv_raw, att_raw, response_start=response_start)
if rt_min is not None:
resp_mins_vals.append(rt_min)
all_resp_mins.append(rt_min)
sla_target = crit_sla if comp.get("priority") == "critical" else non_crit_sla
resp_scores.append(_compute_response_score(rt_min / 60.0, sla_target))
uptime_mins = max(0, sched_mins_per_asset - downtime_mins)
uptime_pct = (uptime_mins / float(sched_mins_per_asset)) * 100.0 if sched_mins_per_asset > 0 else 100.0
mttr_hours = round(sum(mttr_vals) / len(mttr_vals), 2) if mttr_vals else None
mtbf_hours = (
round((sched_hours_per_asset - (downtime_mins / 60.0)) / float(period_breakdown_count), 2)
if period_breakdown_count > 0
else None
)
avg_resp_mins = round(sum(resp_mins_vals) / len(resp_mins_vals), 1) if resp_mins_vals else None
# PM compliance in period: completed on time (completed_date <= planned_date) / due in period
pm_recs = pm_by_asset.get(aid, [])
due_in_period = len(pm_recs)
on_time_in_period = 0
for rec in pm_recs:
if rec.get("status") == "completed":
p_d = _to_date(rec.get("planned_date"))
c_d = _to_date(rec.get("completed_date"))
if p_d is not None and c_d is not None and c_d <= p_d:
on_time_in_period += 1
total_pm_due += due_in_period
total_pm_on_time += on_time_in_period
pm_compliance_pct = (
(on_time_in_period / float(due_in_period)) * 100.0 if due_in_period > 0 else 100.0
)
response_score = sum(resp_scores) / len(resp_scores) if resp_scores else 100.0
is_repeat = repeat_window_by_asset.get(aid, 0) >= repeat_cnt
repeat_free_score = 0.0 if is_repeat else 100.0
w = EFFICIENCY_WEIGHTS
uptime_part = w["uptime"] * uptime_pct
pm_part = w["pm_compliance"] * pm_compliance_pct
resp_part = w["response"] * response_score
repeat_part = w["repeat_free"] * repeat_free_score
score = uptime_part + pm_part + resp_part + repeat_part
per_asset.append(
{
"asset_id": aid,
"asset_code": a["asset_code"],
"asset_name": a["name"],
"department_name": a.get("department_name") or "Unassigned",
"category_name": a.get("category_name") or "Uncategorized",
"scheduled_minutes": sched_mins_per_asset,
"downtime_minutes": downtime_mins,
"uptime_pct": round(uptime_pct, 2),
"mttr_hours": mttr_hours,
"mtbf_hours": mtbf_hours,
"mtbf_formatted": f"{mtbf_hours:.1f} hrs" if mtbf_hours is not None else "No failures",
"avg_response_minutes": avg_resp_mins,
"pm_compliance_pct": round(pm_compliance_pct, 2),
"pm_due_count": due_in_period,
"pm_on_time_count": on_time_in_period,
"response_score": round(response_score, 2),
"repeat_free_score": round(repeat_free_score, 2),
"efficiency_score": round(score, 2),
"parts": {
"uptime": round(uptime_part, 2),
"pm_compliance": round(pm_part, 2),
"response": round(resp_part, 2),
"repeat_free": round(repeat_part, 2),
},
}
)
def _aggregate_group(rows: list[dict[str, Any]], key_field: str, group_type: str) -> list[dict[str, Any]]:
buckets: dict[str, list[dict[str, Any]]] = {}
for r in rows:
buckets.setdefault(r[key_field], []).append(r)
out: list[dict[str, Any]] = []
for gname, items in sorted(buckets.items()):
tot_w = sum(i["scheduled_minutes"] for i in items)
if tot_w <= 0:
continue
w_avg = lambda f: round(sum(i[f] * i["scheduled_minutes"] for i in items) / tot_w, 2)
w_part = lambda p: round(sum(i["parts"][p] * i["scheduled_minutes"] for i in items) / tot_w, 2)
g_mttr = [i["mttr_hours"] for i in items if i["mttr_hours"] is not None]
g_mtbf = [i["mtbf_hours"] for i in items if i["mtbf_hours"] is not None]
out.append(
{
"group": gname,
"group_type": group_type,
"asset_count": len(items),
"uptime_pct": w_avg("uptime_pct"),
"pm_compliance_pct": w_avg("pm_compliance_pct"),
"response_score": w_avg("response_score"),
"repeat_free_score": w_avg("repeat_free_score"),
"mttr_hours": round(sum(g_mttr) / len(g_mttr), 2) if g_mttr else None,
"mtbf_hours": round(sum(g_mtbf) / len(g_mtbf), 2) if g_mtbf else None,
"mtbf_formatted": (
f"{(sum(g_mtbf) / len(g_mtbf)):.1f} hrs" if g_mtbf else "No failures"
),
"efficiency_score": w_avg("efficiency_score"),
"parts": {
"uptime": w_part("uptime"),
"pm_compliance": w_part("pm_compliance"),
"response": w_part("response"),
"repeat_free": w_part("repeat_free"),
},
}
)
out.sort(key=lambda r: (r["efficiency_score"], r["group"]))
return out
by_department = _aggregate_group(per_asset, "department_name", "department")
by_category = _aggregate_group(per_asset, "category_name", "category")
tot_sched = sum(r["scheduled_minutes"] for r in per_asset)
if tot_sched > 0:
avg_uptime = round(sum(r["uptime_pct"] * r["scheduled_minutes"] for r in per_asset) / tot_sched, 2)
avg_score = round(sum(r["efficiency_score"] * r["scheduled_minutes"] for r in per_asset) / tot_sched, 2)
overall_pm_pct = (
round((total_pm_on_time / float(total_pm_due)) * 100.0, 2)
if total_pm_due > 0
else 100.0
)
else:
avg_uptime = 0.0
avg_score = 0.0
overall_pm_pct = 0.0
overall_mttr = round(sum(all_mttr) / len(all_mttr), 2) if all_mttr else None
total_breakdowns = sum(
1
for a in active_assets
for c in complaints_by_asset.get(int(a["id"]), [])
if _to_date(c.get("registered_at")) is not None
and period_start <= _to_date(c.get("registered_at")) <= period_end
)
total_dt_hours = sum(r["downtime_minutes"] for r in per_asset) / 60.0
total_sched_hours = tot_sched / 60.0
overall_mtbf = (
round((total_sched_hours - total_dt_hours) / float(total_breakdowns), 2)
if total_breakdowns > 0
else None
)
overall_resp = round(sum(all_resp_mins) / len(all_resp_mins), 1) if all_resp_mins else None
evidence: list[dict[str, Any]] = [
make_metric("m_eff_avg_score", "Average Efficiency Score", avg_score, "score", f"{avg_score:.1f} / 100"),
make_metric("m_eff_avg_uptime", "Average Uptime", avg_uptime, "%"),
make_metric("m_eff_pm_compliance", "PM On-Time Compliance", overall_pm_pct, "%"),
make_metric(
"m_eff_mttr_hours",
"Mean Time To Repair (MTTR)",
overall_mttr,
"hours",
f"{overall_mttr:.1f} hrs" if overall_mttr is not None else "No repairs",
),
make_metric(
"m_eff_mtbf_hours",
"Mean Time Between Failures (MTBF)",
overall_mtbf,
"hours",
f"{overall_mtbf:.1f} hrs" if overall_mtbf is not None else "No failures",
),
make_metric(
"m_eff_avg_response_min",
"Average Response Time",
overall_resp,
"minutes",
f"{overall_resp:.1f} mins" if overall_resp is not None else "—",
),
]
for g in by_department:
evidence.append(
make_metric(
f"m_eff_dept_{_slug(g['group'])}",
f"Efficiency Score ({g['group']})",
g["efficiency_score"],
"score",
f"{g['efficiency_score']:.1f}",
)
)
return {
"weights": dict(EFFICIENCY_WEIGHTS),
"summary": {
"avg_uptime_pct": avg_uptime,
"mttr_hours": overall_mttr,
"mtbf_hours": overall_mtbf,
"mtbf_formatted": f"{overall_mtbf:.1f} hrs" if overall_mtbf is not None else "No failures",
"avg_response_minutes": overall_resp,
"pm_compliance_pct": overall_pm_pct,
"avg_efficiency_score": avg_score,
"assets_evaluated": len(per_asset),
},
"per_asset": per_asset,
"by_department": by_department,
"by_category": by_category,
"evidence": evidence,
}
# ---------------------------------------------------------------------------
# Thin DB Loaders & Section Builders
# ---------------------------------------------------------------------------
def load_ai_settings(db: Session) -> dict[str, Any]:
out: dict[str, Any] = {}
for key, default in DEFAULT_AI_SETTINGS.items():
val = get_setting_value(db, key, default)
out[key] = default if val is None else val
return out
def resolve_period(
db: Session,
period: str = "12m",
date_from: Optional[date] = None,
date_to: Optional[date] = None,
) -> tuple[date, date]:
today = effective_today(db)
if period == "custom" and date_from is not None and date_to is not None:
return (min(date_from, date_to), max(date_from, date_to))
months_map = {"3m": 3, "6m": 6, "12m": 12}
months = months_map.get(period, 12)
start = add_months(today, -months)
return (start, today)
def load_ai_dataset(
db: Session,
user: User,
period_start: date,
period_end: date,
department_id: Optional[int] = None,
category_id: Optional[int] = None,
) -> dict[str, Any]:
today = effective_today(db)
eff_now = effective_now_utc(db)
cfg = load_ai_settings(db)
scope = resolve_department_scope(user, department_id)
if scope.is_empty:
return {
"today": today,
"now_utc": eff_now,
"period_start": period_start,
"period_end": period_end,
"settings": cfg,
"assets": [],
"contracts_by_asset": {},
"complaints": [],
"complaints_by_asset": {},
"pm_schedules_by_asset": {},
"pm_records": [],
"pm_records_by_asset": {},
"coverage_by_asset": {},
"cal_records_by_asset": {},
"cal_plans_by_asset": {},
"warranties_by_asset": {},
}
asset_q = db.query(Asset).options(
joinedload(Asset.category),
joinedload(Asset.department),
joinedload(Asset.location),
)
if scope.department_id is not None:
asset_q = asset_q.filter(Asset.department_id == scope.department_id)
if category_id is not None:
asset_q = asset_q.filter(Asset.category_id == category_id)
asset_objs = asset_q.order_by(Asset.asset_code.asc()).all()
asset_ids = [a.id for a in asset_objs]
assets_plain: list[dict[str, Any]] = [
{
"id": a.id,
"asset_code": a.asset_code,
"name": a.name,
"category_id": a.category_id,
"category_name": a.category.name if a.category else "Uncategorized",
"category_default_useful_life_years": (
a.category.default_useful_life_years if a.category else None
),
"department_id": a.department_id,
"department_name": a.department.name if a.department else "Unassigned",
"purchase_value": a.purchase_value,
"acquisition_mode": a.acquisition_mode or "purchased",
"monthly_rent": a.monthly_rent,
"useful_life_years": a.useful_life_years,
"salvage_pct": a.salvage_pct,
"depreciation_method": a.depreciation_method,
"purchase_date": a.purchase_date,
"installation_date": a.installation_date,
"status": a.status,
"criticality": a.criticality,
"requires_calibration": a.requires_calibration,
}
for a in asset_objs
]
contracts_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids}
if asset_ids:
for c in db.query(Contract).filter(Contract.asset_id.in_(asset_ids)).all():
contracts_by_asset[c.asset_id].append(
{
"id": c.id,
"asset_id": c.asset_id,
"contract_type": c.contract_type,
"provider_id": c.provider_id,
"start_date": c.start_date,
"end_date": c.end_date,
"contract_value": c.contract_value,
"is_superseded": c.is_superseded,
}
)
complaints_plain: list[dict[str, Any]] = []
complaints_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids}
if asset_ids:
for comp in db.query(Complaint).filter(Complaint.asset_id.in_(asset_ids)).all():
item = {
"id": comp.id,
"complaint_no": comp.complaint_no,
"asset_id": comp.asset_id,
"priority": comp.priority,
"call_status": comp.call_status,
"registered_at": comp.registered_at,
"received_at": comp.received_at,
"attended_at": comp.attended_at,
"restored_at": comp.restored_at,
"closed_at": comp.closed_at,
"repair_cost": comp.repair_cost,
"spare_cost_estimate": comp.spare_cost_estimate,
"coverage_tag": comp.coverage_tag,
}
complaints_plain.append(item)
complaints_by_asset[comp.asset_id].append(item)
pm_schedules_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids}
if asset_ids:
for s in db.query(PMSchedule).filter(PMSchedule.asset_id.in_(asset_ids)).all():
pm_schedules_by_asset[s.asset_id].append(
{
"id": s.id,
"asset_id": s.asset_id,
"service_mode": s.service_mode,
"frequency_months": s.frequency_months,
"cost_per_visit": s.cost_per_visit,
"next_planned_date": s.next_planned_date,
"is_active": s.is_active,
}
)
pm_records_plain: list[dict[str, Any]] = []
pm_records_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids}
if asset_ids:
for r in db.query(PMRecord).filter(PMRecord.asset_id.in_(asset_ids)).all():
item = {
"id": r.id,
"schedule_id": r.schedule_id,
"asset_id": r.asset_id,
"planned_date": r.planned_date,
"completed_date": r.completed_date,
"status": r.status,
}
pm_records_plain.append(item)
pm_records_by_asset[r.asset_id].append(item)
cal_plans_by_asset: dict[int, dict[str, Any]] = {}
cal_records_by_asset: dict[int, list[dict[str, Any]]] = {aid: [] for aid in asset_ids}
if asset_ids:
for p in db.query(CalibrationPlan).filter(CalibrationPlan.asset_id.in_(asset_ids), CalibrationPlan.is_active.is_(True)).all():
cal_plans_by_asset[p.asset_id] = {
"id": p.id,
"asset_id": p.asset_id,
"next_due_date": p.next_due_date,
}
for cr in db.query(CalibrationRecord).filter(CalibrationRecord.asset_id.in_(asset_ids)).all():
cal_records_by_asset[cr.asset_id].append(
{
"id": cr.id,
"asset_id": cr.asset_id,
"due_date": cr.due_date,
"completed_date": cr.completed_date,
"status": cr.status,
}
)
coverage_by_asset = get_coverage_map(db, asset_ids, today) if asset_ids else {}
return {
"today": today,
"now_utc": eff_now,
"period_start": period_start,
"period_end": period_end,
"settings": cfg,
"assets": assets_plain,
"contracts_by_asset": contracts_by_asset,
"complaints": complaints_plain,
"complaints_by_asset": complaints_by_asset,
"pm_schedules_by_asset": pm_schedules_by_asset,
"pm_records": pm_records_plain,
"pm_records_by_asset": pm_records_by_asset,
"coverage_by_asset": coverage_by_asset,
"cal_plans_by_asset": cal_plans_by_asset,
"cal_records_by_asset": cal_records_by_asset,
}
def compute_comparison_from_dataset(dataset: dict[str, Any]) -> dict[str, Any]:
cfg = dataset["settings"]
today = dataset["today"]
horizon = int(cfg["comparison_horizon_years"])
latest_n = int(cfg["latest_equipment_count"])
# Latest equipment = most recent installation_date (fallback purchase_date)
def _recency_key(a: dict[str, Any]) -> tuple[date, str]:
d = _to_date(a.get("installation_date")) or _to_date(a.get("purchase_date")) or date.min
return (d, a["asset_code"])
dated_assets = [
a
for a in dataset["assets"]
if (_to_date(a.get("installation_date")) or _to_date(a.get("purchase_date"))) is not None
]
dated_assets.sort(key=lambda a: (_recency_key(a)[0], a["asset_code"]), reverse=True)
latest_assets = dated_assets[:latest_n]
rows: list[dict[str, Any]] = []
chart_data: list[dict[str, Any]] = []
evidence: list[dict[str, Any]] = [
make_metric("m_cmp_horizon_years", "Comparison Horizon", horizon, "years", f"{horizon} years"),
make_metric("m_cmp_latest_count", "Latest Equipment Evaluated", len(latest_assets), "count"),
]
lowest_counts: dict[str, int] = {"in_house": 0, "outsourced": 0, "rent": 0}
total_potential_savings = 0.0
for a in latest_assets:
aid = int(a["id"])
comp = scenario_comparison(
a,
dataset["contracts_by_asset"].get(aid, []),
dataset["complaints_by_asset"].get(aid, []),
dataset["pm_schedules_by_asset"].get(aid, []),
horizon_years=horizon,
as_of=today,
settings=cfg,
)
sc = comp["scenarios"]
if comp["lowest_scenario"] in lowest_counts:
lowest_counts[comp["lowest_scenario"]] += 1
if comp["savings_vs_next"] is not None:
total_potential_savings += float(comp["savings_vs_next"])
slug = _slug(a["asset_code"])
if comp["lowest_cost"] is not None:
evidence.append(
make_metric(
f"m_cmp_lowest_{slug}",
f"Lowest {horizon}-yr Cost ({a['asset_code']} - {comp['lowest_scenario_label']})",
comp["lowest_cost"],
"INR",
)
)
if comp["savings_vs_next"] is not None:
evidence.append(
make_metric(
f"m_cmp_diff_{slug}",
f"Savings vs Next Option ({a['asset_code']})",
comp["savings_vs_next"],
"INR",
)
)
rows.append(
{
"asset_id": aid,
"asset_code": a["asset_code"],
"asset_name": a["name"],
"department_name": a["department_name"],
"category_name": a["category_name"],
"installation_date": str(a["installation_date"]) if a.get("installation_date") else None,
"purchase_date": str(a["purchase_date"]) if a.get("purchase_date") else None,
"purchase_value": a.get("purchase_value"),
"in_house_cost": sc["in_house"]["total_cost"],
"in_house_reason": sc["in_house"]["insufficient_reason"],
"outsourced_cost": sc["outsourced"]["total_cost"],
"outsourced_reason": sc["outsourced"]["insufficient_reason"],
"rent_cost": sc["rent"]["total_cost"],
"rent_reason": sc["rent"]["insufficient_reason"],
"lowest_scenario": comp["lowest_scenario"],
"lowest_scenario_label": comp["lowest_scenario_label"],
"lowest_cost": comp["lowest_cost"],
"savings_vs_next": comp["savings_vs_next"],
"current_setup": comp["current_setup"],
"inputs_used": comp["inputs_used"],
}
)
chart_data.append(
{
"asset_code": a["asset_code"],
"asset_name": a["name"],
"in_house": sc["in_house"]["total_cost"],
"outsourced": sc["outsourced"]["total_cost"],
"rent": sc["rent"]["total_cost"],
}
)
evidence.append(
make_metric("m_cmp_inhouse_wins", "Equipment Where In-House Is Lowest", lowest_counts["in_house"], "count")
)
evidence.append(
make_metric("m_cmp_outsourced_wins", "Equipment Where Outsourced Is Lowest", lowest_counts["outsourced"], "count")
)
evidence.append(
make_metric("m_cmp_rent_wins", "Equipment Where Rent Is Lowest", lowest_counts["rent"], "count")
)
return {
"section": "comparison",
"title": "Comparison: In-House vs Outsourced vs Rent",
"horizon_years": horizon,
"summary": {
"latest_count": len(latest_assets),
"horizon_years": horizon,
"in_house_lowest_count": lowest_counts["in_house"],
"outsourced_lowest_count": lowest_counts["outsourced"],
"rent_lowest_count": lowest_counts["rent"],
},
"rows": rows,
"chart_data": chart_data,
"metrics": evidence,
"how_calculated": {
"formulas": [
"Buy + In-House = (Purchase Value - Book Value at Horizon) + Horizon × Annual In-House PM Cost + Horizon × Annual Breakdown Cost",
"Buy + Outsourced (AMC/CMC) = (Purchase Value - Book Value at Horizon) + Horizon × Annual Contract Cost + Horizon × Annual Breakdown Cost (CMC excludes spare cost estimate)",
"Rent = Monthly Rent × 12 × Horizon",
],
"latest_equipment_rule": f"Top {latest_n} assets ordered by most recent installation_date (falling back to purchase_date).",
"missing_data_rule": "Any missing required input marks that scenario 'Insufficient data: <input>' and excludes it from totals.",
"settings_used": {
"comparison_horizon_years": horizon,
"latest_equipment_count": latest_n,
},
},
}
def compute_depreciation_from_dataset(dataset: dict[str, Any]) -> dict[str, Any]:
cfg = dataset["settings"]
today = dataset["today"]
threshold = float(cfg["replacement_review_ratio"])
rows: list[dict[str, Any]] = []
curves_by_asset: dict[str, list[dict[str, Any]]] = {}
total_purchase = 0.0
total_book = 0.0
total_accum = 0.0
total_maint = 0.0
fully_dep_count = 0
review_flag_count = 0
excluded_count = 0
for a in dataset["assets"]:
aid = int(a["id"])
dep = depreciation(a, today, cfg)
ca = cost_analysis(
a,
dataset["contracts_by_asset"].get(aid, []),
dataset["complaints_by_asset"].get(aid, []),
dataset["pm_schedules_by_asset"].get(aid, []),
dataset["pm_records_by_asset"].get(aid, []),
today,
cfg,
)
if dep["applicable"]:
total_purchase += float(a["purchase_value"])
total_book += float(dep["book_value"])
total_accum += float(dep["accumulated_depreciation"])
total_maint += float(ca["maintenance_cost"])
if dep["fully_depreciated"]:
fully_dep_count += 1
curves_by_asset[a["asset_code"]] = depreciation_curve(a, today, cfg)
else:
excluded_count += 1
if ca["review_flag"]:
review_flag_count += 1
rows.append(
{
"asset_id": aid,
"asset_code": a["asset_code"],
"asset_name": a["name"],
"department_name": a["department_name"],
"category_name": a["category_name"],
"acquisition_mode": a.get("acquisition_mode") or "purchased",
"purchase_value": ca["purchase_value"],
"depreciation_applicable": dep["applicable"],
"depreciation_reason": dep["reason"],
"method": dep["method"],
"useful_life_years": dep["life"],
"book_value": dep["book_value"],
"accumulated_depreciation": dep["accumulated_depreciation"],
"annual_charge": dep["annual_charge"],
"fully_depreciated": dep["fully_depreciated"],
"contract_cost_to_date": ca["contract_cost_to_date"],
"repair_and_spare_cost_to_date": ca["repair_and_spare_cost_to_date"],
"inhouse_pm_cost_to_date": ca["inhouse_pm_cost_to_date"],
"maintenance_cost": ca["maintenance_cost"],
"maintenance_ratio": ca["maintenance_ratio"],
"lifetime_cost": ca["lifetime_cost"],
"cost_per_year_of_use": ca["cost_per_year_of_use"],
"review_flag": ca["review_flag"],
"curve": curves_by_asset.get(a["asset_code"], []),
}
)
evidence: list[dict[str, Any]] = [
make_metric("m_dep_total_purchase_value", "Total Purchase Value (Owned Assets)", round(total_purchase, 2), "INR"),
make_metric("m_dep_total_book_value", "Total Current Book Value", round(total_book, 2), "INR"),
make_metric("m_dep_total_accumulated", "Total Accumulated Depreciation", round(total_accum, 2), "INR"),
make_metric("m_dep_total_maintenance", "Total Maintenance Cost to Date", round(total_maint, 2), "INR"),
make_metric("m_dep_fully_depreciated_count", "Fully Depreciated Assets", fully_dep_count, "count"),
make_metric("m_dep_review_flag_count", f"Assets Above {int(threshold * 100)}% Maintenance Ratio", review_flag_count, "count"),
make_metric("m_dep_excluded_count", "Assets Excluded (Rented / Missing Inputs)", excluded_count, "count"),
]
for r in rows:
if r["review_flag"] or r["fully_depreciated"]:
slug = _slug(r["asset_code"])
if r["book_value"] is not None:
evidence.append(
make_metric(
f"m_dep_book_value_{slug}",
f"Book Value ({r['asset_code']})",
r["book_value"],
"INR",
)
)
if r["maintenance_ratio"] is not None:
evidence.append(
make_metric(
f"m_dep_maint_ratio_{slug}",
f"Maintenance Ratio ({r['asset_code']})",
round(r["maintenance_ratio"] * 100.0, 1),
"%",
)
)
default_curve = next((r["curve"] for r in rows if r["curve"]), [])
return {
"section": "depreciation",
"title": "Depreciated Price & Cost Analysis",
"summary": {
"total_purchase_value": round(total_purchase, 2),
"total_book_value": round(total_book, 2),
"total_accumulated_depreciation": round(total_accum, 2),
"total_maintenance_cost": round(total_maint, 2),
"fully_depreciated_count": fully_dep_count,
"review_flag_count": review_flag_count,
"replacement_review_ratio": threshold,
"excluded_count": excluded_count,
},
"rows": rows,
"chart_data": default_curve,
"metrics": evidence,
"how_calculated": {
"formulas": [
"Straight Line: Annual Charge = (Cost - Salvage) / Life; Book Value = max(Salvage, Cost - Annual Charge × Years Elapsed)",
"Written Down Value: Rate = 1 - (Salvage / Cost)^(1 / Life); Book Value = max(Salvage, Cost × (1 - Rate)^Years Elapsed)",
"Maintenance Cost = Prorated Contract Cost + Repair & Spare Cost + Completed In-House PM Cost",
f"Replacement Review Flag = Maintenance Cost / Purchase Value >= {threshold:.2f}",
],
"settings_used": {
"default_useful_life_years": cfg["default_useful_life_years"],
"default_salvage_pct": cfg["default_salvage_pct"],
"default_depreciation_method": cfg["default_depreciation_method"],
"replacement_review_ratio": threshold,
},
},
}
def compute_efficiency_from_dataset(dataset: dict[str, Any]) -> dict[str, Any]:
res = efficiency(
dataset["assets"],
dataset["complaints"],
dataset["pm_records"],
dataset["period_start"],
dataset["period_end"],
dataset["today"],
settings=dataset["settings"],
now_utc=dataset["now_utc"],
)
rows = res["by_department"] + res["by_category"]
chart_data = [
{
"group": g["group"],
"uptime": g["parts"]["uptime"],
"pm_compliance": g["parts"]["pm_compliance"],
"response": g["parts"]["response"],
"repeat_free": g["parts"]["repeat_free"],
"efficiency_score": g["efficiency_score"],
}
for g in res["by_department"]
]
return {
"section": "efficiency",
"title": "Equipment Efficiency",
"weights": res["weights"],
"summary": res["summary"],
"rows": rows,
"per_asset": res["per_asset"],
"by_department": res["by_department"],
"by_category": res["by_category"],
"chart_data": chart_data,
"metrics": res["evidence"],
"how_calculated": {
"formulas": [
"Efficiency Score = 0.50 × Uptime% + 0.20 × PM Compliance% + 0.15 × Response Score + 0.15 × Repeat-Free Score",
"Uptime% = (Scheduled Minutes - Downtime Minutes) / Scheduled Minutes × 100",
"MTTR = Mean(Restored or Closed At - Registered At); MTBF = (Scheduled Hours - Downtime Hours) / Breakdown Count",
"Response Score = 100 if Avg Response <= SLA Target, falling linearly to 0 at 4 × SLA Target",
"Department & Category scores are weighted averages of their assets weighted by scheduled operating minutes.",
],
"weights": dict(EFFICIENCY_WEIGHTS),
"settings_used": {
"scheduled_hours_per_day": dataset["settings"]["scheduled_hours_per_day"],
"downtime_end_milestone": dataset["settings"]["downtime_end_milestone"],
"critical_complaint_sla_hours": dataset["settings"]["critical_complaint_sla_hours"],
"non_critical_complaint_sla_hours": dataset["settings"]["non_critical_complaint_sla_hours"],
},
},
}
def compute_breakdown_frequency_from_dataset(dataset: dict[str, Any]) -> dict[str, Any]:
res = breakdown_frequency(
dataset["assets"],
dataset["complaints"],
dataset["period_start"],
dataset["period_end"],
dataset["today"],
settings=dataset["settings"],
now_utc=dataset["now_utc"],
)
return {
"section": "breakdown_frequency",
"title": "Breakdown Frequency & Average Breakdowns",
"summary": res["summary"],
"rows": res["top_10_assets"],
"per_asset": res["per_asset"],
"by_department": res["by_department"],
"by_category": res["by_category"],
"chart_data": {
"monthly_trend": res["monthly_trend"],
"by_department": res["by_department"],
"by_category": res["by_category"],
},
"metrics": res["evidence"],
"how_calculated": {
"formulas": [
"Average Breakdowns per Equipment = Total Breakdowns in Period / Total Assets in Scope (including zero-breakdown assets)",
"Breakdowns per 1,000 Operating Hours = Total Breakdowns / (Assets × Period Days × Scheduled Hours/Day / 1000)",
f"Repeat Failure = Asset has >= {dataset['settings']['repeat_failure_count']} breakdowns within the last {dataset['settings']['repeat_failure_days']} days (from effective today).",
],
"settings_used": {
"repeat_failure_count": dataset["settings"]["repeat_failure_count"],
"repeat_failure_days": dataset["settings"]["repeat_failure_days"],
"scheduled_hours_per_day": dataset["settings"]["scheduled_hours_per_day"],
},
},
}