initial commit
This commit is contained in:
@@ -0,0 +1,434 @@
|
||||
"""
|
||||
Rule-based Suggestions Engine (S1-S8) for AI Reports.
|
||||
|
||||
Pure Python deterministic rules with zero LLM involvement. Every suggestion links
|
||||
to concrete evidence metric IDs, uses neutral advisory language (never 'approve',
|
||||
'safe', 'unsafe', 'must buy'), and ends its action text with 'Needs a human decision.'
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import User
|
||||
from .ai_metrics import (
|
||||
_slug,
|
||||
_to_date,
|
||||
compute_breakdown_frequency_from_dataset,
|
||||
compute_comparison_from_dataset,
|
||||
compute_depreciation_from_dataset,
|
||||
compute_efficiency_from_dataset,
|
||||
format_inr,
|
||||
load_ai_dataset,
|
||||
make_metric,
|
||||
scenario_comparison,
|
||||
)
|
||||
|
||||
SEVERITY_RANK: dict[str, int] = {"red": 0, "yellow": 1, "info": 2}
|
||||
|
||||
SCENARIO_DISPLAY_NAMES: dict[str, str] = {
|
||||
"in_house": "Buy + In-House Maintenance",
|
||||
"outsourced": "Buy + Outsourced Contract (AMC/CMC)",
|
||||
"rent": "Rent",
|
||||
}
|
||||
|
||||
|
||||
def generate_suggestions(
|
||||
dataset: dict[str, Any],
|
||||
*,
|
||||
comparison: Optional[dict[str, Any]] = None,
|
||||
depreciation_data: Optional[dict[str, Any]] = None,
|
||||
efficiency_data: Optional[dict[str, Any]] = None,
|
||||
breakdown_data: Optional[dict[str, Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Generate sorted S1-S8 suggestions and their complete referenced evidence list."""
|
||||
cfg = dataset["settings"]
|
||||
today: date = dataset["today"]
|
||||
contract_lead_days = int(cfg.get("contract_expiry_alert_days", 30))
|
||||
horizon = int(cfg.get("comparison_horizon_years", 5))
|
||||
review_threshold = float(cfg.get("replacement_review_ratio", 0.4))
|
||||
|
||||
cmp_data = comparison or compute_comparison_from_dataset(dataset)
|
||||
dep_data = depreciation_data or compute_depreciation_from_dataset(dataset)
|
||||
eff_data = efficiency_data or compute_efficiency_from_dataset(dataset)
|
||||
bf_data = breakdown_data or compute_breakdown_frequency_from_dataset(dataset)
|
||||
|
||||
evidence_by_id: dict[str, dict[str, Any]] = {}
|
||||
for sec in (cmp_data, dep_data, eff_data, bf_data):
|
||||
for m in sec.get("metrics", []):
|
||||
evidence_by_id[m["id"]] = m
|
||||
|
||||
def _add_ev(metric: dict[str, Any]) -> str:
|
||||
evidence_by_id[metric["id"]] = metric
|
||||
return metric["id"]
|
||||
|
||||
dep_by_asset = {int(r["asset_id"]): r for r in dep_data.get("rows", [])}
|
||||
eff_by_asset = {int(r["asset_id"]): r for r in eff_data.get("per_asset", [])}
|
||||
bf_by_asset = {int(r["asset_id"]): r for r in bf_data.get("per_asset", [])}
|
||||
cov_by_asset = dataset.get("coverage_by_asset", {})
|
||||
|
||||
suggestions: list[dict[str, Any]] = []
|
||||
|
||||
for a in dataset.get("assets", []):
|
||||
aid = int(a["id"])
|
||||
code = a["asset_code"]
|
||||
name = a["name"]
|
||||
slug = _slug(code)
|
||||
|
||||
bf_row = bf_by_asset.get(aid, {})
|
||||
dep_row = dep_by_asset.get(aid, {})
|
||||
eff_row = eff_by_asset.get(aid, {})
|
||||
cov = cov_by_asset.get(aid, {})
|
||||
|
||||
period_b = int(bf_row.get("breakdown_count", 0))
|
||||
repeat_cnt_val = int(bf_row.get("repeat_window_count", 0))
|
||||
is_repeat = bool(bf_row.get("repeat_failure", False))
|
||||
|
||||
# --- S1: Repeat failure ---
|
||||
if is_repeat:
|
||||
sev = "red" if repeat_cnt_val >= 4 else "yellow"
|
||||
ev_id = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_repeat_window_{slug}",
|
||||
f"Breakdowns in Last {cfg.get('repeat_failure_days', 90)}d ({code})",
|
||||
repeat_cnt_val,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S1_{slug}",
|
||||
"rule": "S1",
|
||||
"severity": sev,
|
||||
"title": f"Repeat failure on {code} ({name})",
|
||||
"detail": (
|
||||
f"{code} recorded {repeat_cnt_val} breakdowns within the last "
|
||||
f"{cfg.get('repeat_failure_days', 90)} days."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_id],
|
||||
"action_for_human": "Review root cause and escalate to the vendor. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S2: Out-of-contract with >= 2 breakdowns in period ---
|
||||
cov_tag = cov.get("tag", "out_of_contract")
|
||||
if cov_tag == "out_of_contract" and period_b >= 2:
|
||||
ev_b = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_count_{slug}",
|
||||
f"Breakdowns in Period ({code})",
|
||||
period_b,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
ev_cov = _add_ev(
|
||||
make_metric(
|
||||
f"m_cov_tag_{slug}",
|
||||
f"Current Coverage ({code})",
|
||||
"out_of_contract",
|
||||
"status",
|
||||
"Out of Contract",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S2_{slug}",
|
||||
"rule": "S2",
|
||||
"severity": "yellow",
|
||||
"title": f"Out-of-contract equipment with recurring breakdowns: {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has no active warranty or AMC/CMC contract and logged "
|
||||
f"{period_b} breakdowns in the selected period."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_b, ev_cov],
|
||||
"action_for_human": "Consider an AMC/CMC. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S3: Active AMC/CMC contract ends within contract lead days AND >= 1 breakdown in period ---
|
||||
if cov_tag in ("amc", "cmc") and period_b >= 1:
|
||||
days_left = cov.get("days_left")
|
||||
if days_left is not None and 0 <= int(days_left) <= contract_lead_days:
|
||||
ev_days = _add_ev(
|
||||
make_metric(
|
||||
f"m_cov_days_left_{slug}",
|
||||
f"Contract Days Remaining ({code})",
|
||||
int(days_left),
|
||||
"days",
|
||||
f"{int(days_left)} days",
|
||||
)
|
||||
)
|
||||
ev_b = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_count_{slug}",
|
||||
f"Breakdowns in Period ({code})",
|
||||
period_b,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S3_{slug}",
|
||||
"rule": "S3",
|
||||
"severity": "yellow",
|
||||
"title": f"Expiring {cov_tag.upper()} with recent breakdowns: {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has an active {cov_tag.upper()} expiring in {int(days_left)} day(s) "
|
||||
f"and recorded {period_b} breakdown(s) in the selected period."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_days, ev_b],
|
||||
"action_for_human": "Renewal review before expiry. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S4: maintenance_ratio >= replacement_review_ratio ---
|
||||
maint_ratio = dep_row.get("maintenance_ratio")
|
||||
if maint_ratio is not None and float(maint_ratio) >= review_threshold:
|
||||
ratio_f = float(maint_ratio)
|
||||
sev = "red" if ratio_f >= 1.0 else "yellow"
|
||||
ev_ratio = _add_ev(
|
||||
make_metric(
|
||||
f"m_dep_maint_ratio_{slug}",
|
||||
f"Maintenance Ratio ({code})",
|
||||
round(ratio_f * 100.0, 1),
|
||||
"%",
|
||||
)
|
||||
)
|
||||
ev_maint = _add_ev(
|
||||
make_metric(
|
||||
f"m_dep_maint_cost_{slug}",
|
||||
f"Cumulative Maintenance Cost ({code})",
|
||||
dep_row.get("maintenance_cost"),
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S4_{slug}",
|
||||
"rule": "S4",
|
||||
"severity": sev,
|
||||
"title": f"High maintenance-to-purchase ratio on {code} ({ratio_f * 100:.1f}%)",
|
||||
"detail": (
|
||||
f"Cumulative maintenance cost for {code} ({name}) reached "
|
||||
f"{format_inr(dep_row.get('maintenance_cost'))}, which is {ratio_f * 100:.1f}% "
|
||||
f"of purchase value ({format_inr(dep_row.get('purchase_value'))})."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_ratio, ev_maint],
|
||||
"action_for_human": "Replacement review. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S5: scenario_comparison shows another scenario >= 10% cheaper than current set-up ---
|
||||
sc_res = scenario_comparison(
|
||||
a,
|
||||
dataset.get("contracts_by_asset", {}).get(aid, []),
|
||||
dataset.get("complaints_by_asset", {}).get(aid, []),
|
||||
dataset.get("pm_schedules_by_asset", {}).get(aid, []),
|
||||
horizon_years=horizon,
|
||||
as_of=today,
|
||||
settings=cfg,
|
||||
)
|
||||
cur_setup = sc_res.get("current_setup")
|
||||
lowest_key = sc_res.get("lowest_scenario")
|
||||
if cur_setup and lowest_key and lowest_key != cur_setup:
|
||||
cur_scen = sc_res["scenarios"].get(cur_setup, {})
|
||||
low_scen = sc_res["scenarios"].get(lowest_key, {})
|
||||
if cur_scen.get("available") and low_scen.get("available"):
|
||||
cur_cost = float(cur_scen["total_cost"])
|
||||
low_cost = float(low_scen["total_cost"])
|
||||
if cur_cost > 0 and (cur_cost - low_cost) / cur_cost >= 0.10:
|
||||
savings = round(cur_cost - low_cost, 2)
|
||||
pct_save = round((savings / cur_cost) * 100.0, 1)
|
||||
ev_cur = _add_ev(
|
||||
make_metric(
|
||||
f"m_cmp_current_{slug}",
|
||||
f"Current {horizon}-yr Estimate ({code} - {SCENARIO_DISPLAY_NAMES.get(cur_setup, cur_setup)})",
|
||||
cur_cost,
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
ev_low = _add_ev(
|
||||
make_metric(
|
||||
f"m_cmp_lowest_{slug}",
|
||||
f"Lowest {horizon}-yr Estimate ({code} - {SCENARIO_DISPLAY_NAMES.get(lowest_key, lowest_key)})",
|
||||
low_cost,
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
target_label = SCENARIO_DISPLAY_NAMES.get(lowest_key, lowest_key)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S5_{slug}",
|
||||
"rule": "S5",
|
||||
"severity": "info",
|
||||
"title": f"Lower {horizon}-year cost option identified for {code}",
|
||||
"detail": (
|
||||
f"For {code} ({name}), {target_label} ({format_inr(low_cost)}) is "
|
||||
f"{pct_save:.1f}% ({format_inr(savings)}) below current {SCENARIO_DISPLAY_NAMES.get(cur_setup, cur_setup)} "
|
||||
f"({format_inr(cur_cost)}) over {horizon} years."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_cur, ev_low],
|
||||
"action_for_human": f"Evaluate {target_label}. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S6: PM overdue AND >= 1 breakdown in period ---
|
||||
pm_recs = dataset.get("pm_records_by_asset", {}).get(aid, [])
|
||||
overdue_pm_days = 0
|
||||
for rec in pm_recs:
|
||||
if rec.get("status") not in ("completed", "rescheduled"):
|
||||
p_d = _to_date(rec.get("planned_date"))
|
||||
if p_d is not None and p_d < today:
|
||||
overdue_pm_days = max(overdue_pm_days, (today - p_d).days)
|
||||
if overdue_pm_days > 0 and period_b >= 1:
|
||||
ev_pm = _add_ev(
|
||||
make_metric(
|
||||
f"m_pm_overdue_days_{slug}",
|
||||
f"PM Overdue Days ({code})",
|
||||
overdue_pm_days,
|
||||
"days",
|
||||
f"{overdue_pm_days} days overdue",
|
||||
)
|
||||
)
|
||||
ev_b = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_count_{slug}",
|
||||
f"Breakdowns in Period ({code})",
|
||||
period_b,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S6_{slug}",
|
||||
"rule": "S6",
|
||||
"severity": "yellow",
|
||||
"title": f"Overdue PM with active breakdowns on {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has preventive maintenance overdue by {overdue_pm_days} day(s) "
|
||||
f"and recorded {period_b} breakdown(s) in the period."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_pm, ev_b],
|
||||
"action_for_human": "Clear overdue PM. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S7: Calibration overdue ---
|
||||
cal_recs = dataset.get("cal_records_by_asset", {}).get(aid, [])
|
||||
cal_plan = dataset.get("cal_plans_by_asset", {}).get(aid)
|
||||
cal_overdue_days = 0
|
||||
open_cal_found = False
|
||||
for cr in cal_recs:
|
||||
if cr.get("status") != "completed":
|
||||
open_cal_found = True
|
||||
d_d = _to_date(cr.get("due_date"))
|
||||
if d_d is not None and d_d < today:
|
||||
cal_overdue_days = max(cal_overdue_days, (today - d_d).days)
|
||||
if not open_cal_found and cal_plan:
|
||||
d_d = _to_date(cal_plan.get("next_due_date"))
|
||||
if d_d is not None and d_d < today:
|
||||
cal_overdue_days = (today - d_d).days
|
||||
|
||||
if cal_overdue_days > 0:
|
||||
sev = "red" if cal_overdue_days > 30 else "yellow"
|
||||
ev_cal = _add_ev(
|
||||
make_metric(
|
||||
f"m_cal_overdue_days_{slug}",
|
||||
f"Calibration Overdue Days ({code})",
|
||||
cal_overdue_days,
|
||||
"days",
|
||||
f"{cal_overdue_days} days overdue",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S7_{slug}",
|
||||
"rule": "S7",
|
||||
"severity": sev,
|
||||
"title": f"Calibration overdue on {code} ({cal_overdue_days} days)",
|
||||
"detail": (
|
||||
f"Scheduled calibration for {code} ({name}) is overdue by {cal_overdue_days} day(s)."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_cal],
|
||||
"action_for_human": "Complete calibration. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S8: Fully depreciated AND efficiency_score < 80 ---
|
||||
eff_score = eff_row.get("efficiency_score")
|
||||
if dep_row.get("fully_depreciated") and eff_score is not None and float(eff_score) < 80.0:
|
||||
ev_bv = _add_ev(
|
||||
make_metric(
|
||||
f"m_dep_book_value_{slug}",
|
||||
f"Book Value ({code})",
|
||||
dep_row.get("book_value"),
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
ev_eff = _add_ev(
|
||||
make_metric(
|
||||
f"m_eff_score_{slug}",
|
||||
f"Efficiency Score ({code})",
|
||||
float(eff_score),
|
||||
"score",
|
||||
f"{float(eff_score):.1f} / 100",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S8_{slug}",
|
||||
"rule": "S8",
|
||||
"severity": "yellow",
|
||||
"title": f"Fully depreciated asset with low efficiency: {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has reached the end of its depreciable life "
|
||||
f"(book value {format_inr(dep_row.get('book_value'))}) with an efficiency score of "
|
||||
f"{float(eff_score):.1f} / 100."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_bv, ev_eff],
|
||||
"action_for_human": "Replacement planning. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
suggestions.sort(
|
||||
key=lambda s: (
|
||||
SEVERITY_RANK.get(s["severity"], 9),
|
||||
s["asset_codes"][0] if s["asset_codes"] else "",
|
||||
s["rule"],
|
||||
)
|
||||
)
|
||||
|
||||
return {
|
||||
"suggestions": suggestions,
|
||||
"evidence": list(evidence_by_id.values()),
|
||||
}
|
||||
|
||||
|
||||
def get_suggestions_for_scope(
|
||||
db: Session,
|
||||
user: User,
|
||||
period_start: date,
|
||||
period_end: date,
|
||||
department_id: Optional[int] = None,
|
||||
category_id: Optional[int] = None,
|
||||
) -> dict[str, Any]:
|
||||
dataset = load_ai_dataset(
|
||||
db,
|
||||
user,
|
||||
period_start,
|
||||
period_end,
|
||||
department_id=department_id,
|
||||
category_id=category_id,
|
||||
)
|
||||
return generate_suggestions(dataset)
|
||||
|
||||
Reference in New Issue
Block a user