312 lines
13 KiB
Python
312 lines
13 KiB
Python
from datetime import date, datetime, timedelta, timezone
|
|
import pytest
|
|
|
|
from app.core.time_utils import effective_today
|
|
from app.models import Asset, User
|
|
from app.seed.seed import seed_database
|
|
from app.services.ai_metrics import (
|
|
EFFICIENCY_WEIGHTS,
|
|
_book_value_at_years,
|
|
_compute_response_score,
|
|
breakdown_frequency,
|
|
compute_comparison_from_dataset,
|
|
compute_depreciation_from_dataset,
|
|
cost_analysis,
|
|
depreciation,
|
|
efficiency,
|
|
format_inr,
|
|
load_ai_dataset,
|
|
scenario_comparison,
|
|
)
|
|
|
|
|
|
@pytest.fixture(scope="module", autouse=True)
|
|
def seeded_ai3_db(db, tmp_path_factory):
|
|
upload_dir = tmp_path_factory.mktemp("ai3_test_uploads")
|
|
seed_database(db, upload_dir=upload_dir)
|
|
return upload_dir
|
|
|
|
|
|
def test_depreciation_worked_examples_and_edge_cases():
|
|
# Exact formula worked examples at years_elapsed = 3.0 and 10.0
|
|
bv_sl_3, acc_sl_3, chg_sl_3 = _book_value_at_years(1_000_000.0, 10, 5.0, "straight_line", 3.0)
|
|
assert bv_sl_3 == pytest.approx(715_000.0, abs=1.0)
|
|
assert acc_sl_3 == pytest.approx(285_000.0, abs=1.0)
|
|
assert chg_sl_3 == pytest.approx(95_000.0, abs=1.0)
|
|
|
|
# Written-down value: rate = 1 - (0.05)^(1/10) ≈ 0.25886555 -> book_value(3y) = 1_000_000 * 0.05^0.3 ≈ 407,090.53
|
|
bv_wd_3, acc_wd_3, _ = _book_value_at_years(1_000_000.0, 10, 5.0, "written_down", 3.0)
|
|
expected_wd_3 = 1_000_000.0 * (0.05 ** 0.3)
|
|
assert bv_wd_3 == pytest.approx(expected_wd_3, abs=1.0)
|
|
assert acc_wd_3 == pytest.approx(1_000_000.0 - expected_wd_3, abs=1.0)
|
|
|
|
# After 10 years, both straight_line and written_down equal salvage value (50,000)
|
|
bv_sl_10, _, chg_sl_10 = _book_value_at_years(1_000_000.0, 10, 5.0, "straight_line", 10.0)
|
|
bv_wd_10, _, chg_wd_10 = _book_value_at_years(1_000_000.0, 10, 5.0, "written_down", 10.0)
|
|
assert bv_sl_10 == pytest.approx(50_000.0, abs=1.0)
|
|
assert bv_wd_10 == pytest.approx(50_000.0, abs=1.0)
|
|
assert chg_sl_10 == 0.0
|
|
assert chg_wd_10 == 0.0
|
|
|
|
# Asset dict using purchase_date fallback when installation_date is missing
|
|
asset_sl = {
|
|
"asset_code": "T-SL-1",
|
|
"purchase_value": 1_000_000.0,
|
|
"useful_life_years": 10,
|
|
"salvage_pct": 5.0,
|
|
"depreciation_method": "straight_line",
|
|
"installation_date": None,
|
|
"purchase_date": date(2020, 1, 1),
|
|
}
|
|
res_10y = depreciation(asset_sl, date(2030, 1, 5))
|
|
assert res_10y["applicable"] is True
|
|
assert res_10y["fully_depreciated"] is True
|
|
assert res_10y["book_value"] == pytest.approx(50_000.0, abs=1.0)
|
|
|
|
# Rented asset returns applicable=False, book_value=None, reason='rented'
|
|
rented = {
|
|
"asset_code": "T-RENT-1",
|
|
"acquisition_mode": "rented",
|
|
"monthly_rent": 20_000.0,
|
|
}
|
|
res_rent = depreciation(rented, date(2026, 1, 1))
|
|
assert res_rent["applicable"] is False
|
|
assert res_rent["reason"] == "rented"
|
|
assert res_rent["book_value"] is None
|
|
|
|
# Missing dates -> Insufficient data
|
|
no_dates = {
|
|
"asset_code": "T-NODATE",
|
|
"purchase_value": 500_000.0,
|
|
"installation_date": None,
|
|
"purchase_date": None,
|
|
}
|
|
res_nodate = depreciation(no_dates, date(2026, 1, 1))
|
|
assert res_nodate["applicable"] is False
|
|
assert "Insufficient data" in res_nodate["reason"]
|
|
|
|
# Future installation date -> years_elapsed never negative
|
|
future_asset = {
|
|
"asset_code": "T-FUT",
|
|
"purchase_value": 1_000_000.0,
|
|
"installation_date": date(2028, 1, 1),
|
|
}
|
|
res_fut = depreciation(future_asset, date(2026, 1, 1))
|
|
assert res_fut["years_elapsed"] == 0.0
|
|
assert res_fut["book_value"] == 1_000_000.0
|
|
|
|
|
|
def test_scenario_comparison_worked_example_and_cmc_spare_exclusion():
|
|
as_of = date(2026, 6, 1)
|
|
asset = {
|
|
"id": 1,
|
|
"asset_code": "PHRC-WORK-1",
|
|
"name": "Worked Example Monitor",
|
|
"purchase_value": 1_000_000.0,
|
|
"acquisition_mode": "purchased",
|
|
"monthly_rent": 15_000.0,
|
|
"useful_life_years": 10,
|
|
"salvage_pct": 5.0,
|
|
"depreciation_method": "straight_line",
|
|
"installation_date": date(2025, 6, 1),
|
|
}
|
|
contracts = [
|
|
{
|
|
"id": 10,
|
|
"contract_type": "AMC",
|
|
"start_date": date(2025, 6, 1),
|
|
"end_date": date(2026, 5, 31),
|
|
"contract_value": 80_000.0,
|
|
"is_superseded": False,
|
|
}
|
|
]
|
|
complaints = [
|
|
{
|
|
"id": 100,
|
|
"asset_id": 1,
|
|
"registered_at": datetime(2026, 1, 15, 10, 0, tzinfo=timezone.utc),
|
|
"repair_cost": 12_000.0,
|
|
"spare_cost_estimate": 8_000.0,
|
|
}
|
|
]
|
|
pm_schedules = [
|
|
{
|
|
"id": 50,
|
|
"service_mode": "in_house",
|
|
"frequency_months": 3, # 4 visits/yr * 10,000 = 40,000/yr
|
|
"cost_per_visit": 10_000.0,
|
|
"is_active": True,
|
|
}
|
|
]
|
|
|
|
res = scenario_comparison(asset, contracts, complaints, pm_schedules, horizon_years=5, as_of=as_of)
|
|
assert res["inputs_used"]["book_value_at_horizon"] == pytest.approx(525_000.0, abs=1.0)
|
|
assert res["scenarios"]["in_house"]["total_cost"] == pytest.approx(775_000.0, abs=1.0)
|
|
assert res["scenarios"]["outsourced"]["total_cost"] == pytest.approx(975_000.0, abs=1.0)
|
|
assert res["scenarios"]["rent"]["total_cost"] == pytest.approx(900_000.0, abs=1.0)
|
|
assert res["lowest_scenario"] == "in_house"
|
|
assert res["next_scenario"] == "rent"
|
|
assert res["savings_vs_next"] == pytest.approx(125_000.0, abs=1.0)
|
|
|
|
# Switch contract to CMC -> spare_cost_estimate (8,000/yr * 5 = 40,000) excluded from B
|
|
contracts[0]["contract_type"] = "CMC"
|
|
res_cmc = scenario_comparison(asset, contracts, complaints, pm_schedules, horizon_years=5, as_of=as_of)
|
|
assert res_cmc["scenarios"]["outsourced"]["total_cost"] == pytest.approx(935_000.0, abs=1.0)
|
|
assert res_cmc["scenarios"]["outsourced"]["breakdown"]["cmc_spares_excluded"] is True
|
|
|
|
# Missing inputs return 'Insufficient data: ...' instead of zero
|
|
missing_asset = {"id": 2, "asset_code": "T-MISS", "name": "Missing", "purchase_value": 500_000.0, "monthly_rent": None}
|
|
res_miss = scenario_comparison(missing_asset, [], [], [], horizon_years=5, as_of=as_of)
|
|
assert res_miss["scenarios"]["in_house"]["available"] is False
|
|
assert "Insufficient data" in res_miss["scenarios"]["in_house"]["insufficient_reason"]
|
|
assert res_miss["scenarios"]["outsourced"]["available"] is False
|
|
assert "Insufficient data" in res_miss["scenarios"]["outsourced"]["insufficient_reason"]
|
|
assert res_miss["scenarios"]["rent"]["available"] is False
|
|
assert "Insufficient data" in res_miss["scenarios"]["rent"]["insufficient_reason"]
|
|
|
|
|
|
def test_cost_analysis_proration_and_review_flag():
|
|
as_of = date(2026, 6, 30)
|
|
asset = {
|
|
"id": 1,
|
|
"purchase_value": 200_000.0,
|
|
"acquisition_mode": "purchased",
|
|
"installation_date": date(2024, 6, 30),
|
|
}
|
|
contracts = [
|
|
{
|
|
"id": 1,
|
|
"start_date": date(2026, 1, 1),
|
|
"end_date": date(2026, 12, 31),
|
|
"contract_value": 36_500.0,
|
|
}
|
|
]
|
|
complaints = [
|
|
{"registered_at": datetime(2026, 3, 1, tzinfo=timezone.utc), "repair_cost": 50_000.0, "spare_cost_estimate": 20_000.0},
|
|
]
|
|
pm_schedules = [{"id": 10, "service_mode": "in_house", "cost_per_visit": 5_000.0}]
|
|
pm_records = [
|
|
{"schedule_id": 10, "status": "completed", "completed_date": date(2026, 2, 1)},
|
|
{"schedule_id": 10, "status": "completed", "completed_date": date(2026, 5, 1)},
|
|
{"schedule_id": 10, "status": None, "planned_date": date(2026, 8, 1)},
|
|
]
|
|
res = cost_analysis(asset, contracts, complaints, pm_schedules, pm_records, as_of)
|
|
# Contract prorated 181 / 365 days ≈ 18,100
|
|
assert res["contract_cost_to_date"] == pytest.approx(36_500.0 * (181 / 365.0), abs=1.0)
|
|
assert res["repair_and_spare_cost_to_date"] == 70_000.0
|
|
assert res["inhouse_pm_cost_to_date"] == 10_000.0
|
|
assert res["maintenance_cost"] > 98_000.0
|
|
assert res["maintenance_ratio"] > 0.49
|
|
assert res["review_flag"] is True
|
|
|
|
|
|
def test_breakdown_frequency_and_efficiency_pure_math_and_zero_division():
|
|
# Empty assets -> no zero division
|
|
bf_empty = breakdown_frequency([], [], date(2026, 1, 1), date(2026, 3, 31), date(2026, 3, 31))
|
|
assert bf_empty["summary"]["avg_breakdowns_per_equipment"] == 0.0
|
|
eff_empty = efficiency([], [], [], date(2026, 1, 1), date(2026, 3, 31), date(2026, 3, 31))
|
|
assert eff_empty["summary"]["avg_efficiency_score"] == 0.0
|
|
|
|
# Two assets in ICU: asset 1 has 3 breakdowns, asset 2 has 0 -> avg = 1.5 (zero-breakdown asset counts!)
|
|
assets = [
|
|
{"id": 1, "asset_code": "A-1", "name": "Vent 1", "department_name": "ICU", "category_name": "Life Support", "status": "in_service"},
|
|
{"id": 2, "asset_code": "A-2", "name": "Vent 2", "department_name": "ICU", "category_name": "Life Support", "status": "in_service"},
|
|
]
|
|
t0 = datetime(2026, 3, 1, 10, 0, tzinfo=timezone.utc)
|
|
complaints = [
|
|
{
|
|
"id": 1,
|
|
"asset_id": 1,
|
|
"priority": "critical",
|
|
"registered_at": t0,
|
|
"attended_at": t0 + timedelta(hours=2), # <= 4h SLA -> response_score = 100
|
|
"restored_at": t0 + timedelta(hours=10),
|
|
"closed_at": t0 + timedelta(hours=11),
|
|
},
|
|
{
|
|
"id": 2,
|
|
"asset_id": 1,
|
|
"priority": "critical",
|
|
"registered_at": t0 + timedelta(days=5),
|
|
"attended_at": t0 + timedelta(days=5, hours=4), # == 4h SLA -> 100
|
|
"restored_at": t0 + timedelta(days=5, hours=10),
|
|
"closed_at": t0 + timedelta(days=5, hours=11),
|
|
},
|
|
{
|
|
"id": 3,
|
|
"asset_id": 1,
|
|
"priority": "critical",
|
|
"registered_at": t0 + timedelta(days=10),
|
|
"attended_at": t0 + timedelta(days=10, hours=16), # == 4x SLA -> 0
|
|
"restored_at": t0 + timedelta(days=10, hours=20),
|
|
"closed_at": t0 + timedelta(days=10, hours=21),
|
|
},
|
|
]
|
|
pm_records = [
|
|
{"asset_id": 1, "planned_date": date(2026, 3, 15), "completed_date": date(2026, 3, 15), "status": "completed"},
|
|
{"asset_id": 1, "planned_date": date(2026, 3, 25), "completed_date": None, "status": None}, # 1/2 = 50%
|
|
]
|
|
|
|
bf = breakdown_frequency(assets, complaints, date(2026, 3, 1), date(2026, 3, 31), date(2026, 3, 31))
|
|
assert bf["summary"]["total_breakdowns"] == 3
|
|
assert bf["summary"]["avg_breakdowns_per_equipment"] == 1.5
|
|
assert bf["summary"]["repeat_failure_count"] == 1
|
|
assert bf["by_department"][0]["avg_breakdowns_per_equipment"] == 1.5
|
|
|
|
eff = efficiency(assets, complaints, pm_records, date(2026, 3, 1), date(2026, 3, 31), date(2026, 3, 31))
|
|
assert sum(EFFICIENCY_WEIGHTS.values()) == pytest.approx(1.0)
|
|
a2 = next(r for r in eff["per_asset"] if r["asset_code"] == "A-2")
|
|
assert a2["mtbf_hours"] is None
|
|
assert a2["mtbf_formatted"] == "No failures"
|
|
assert a2["efficiency_score"] == 100.0
|
|
|
|
a1 = next(r for r in eff["per_asset"] if r["asset_code"] == "A-1")
|
|
assert a1["pm_compliance_pct"] == 50.0
|
|
assert a1["repeat_free_score"] == 0.0
|
|
assert a1["response_score"] == pytest.approx((100.0 + 100.0 + 0.0) / 3.0, abs=0.1)
|
|
assert _compute_response_score(10.0, 4.0) == pytest.approx(50.0, abs=0.1)
|
|
assert format_inr(1250000) == "₹12,50,000"
|
|
|
|
|
|
def test_db_loader_department_scoping_and_demo_clock(client, db):
|
|
admin = db.query(User).filter(User.email == "admin@poona.demo").first()
|
|
dept_user = db.query(User).filter(User.email == "dept@poona.demo").first()
|
|
|
|
today = effective_today(db)
|
|
ds_all = load_ai_dataset(db, admin, today - timedelta(days=365), today)
|
|
ds_icu = load_ai_dataset(db, dept_user, today - timedelta(days=365), today)
|
|
|
|
assert len(ds_all["assets"]) == 60
|
|
assert len(ds_icu["assets"]) > 0
|
|
assert len(ds_icu["assets"]) < len(ds_all["assets"])
|
|
assert all(a["department_id"] == dept_user.department_id for a in ds_icu["assets"])
|
|
|
|
# Unassigned department_user -> 0 assets
|
|
unassigned = User(
|
|
name="Unassigned Dept",
|
|
email="unassigned.ai3@poona.demo",
|
|
password_hash="x",
|
|
role="department_user",
|
|
department_id=None,
|
|
is_active=True,
|
|
)
|
|
ds_empty = load_ai_dataset(db, unassigned, today - timedelta(days=365), today)
|
|
assert ds_empty["assets"] == []
|
|
|
|
# Demo clock moves depreciation book values downward as time advances
|
|
dep_now = compute_depreciation_from_dataset(ds_all)
|
|
cmp_now = compute_comparison_from_dataset(ds_all)
|
|
assert len(cmp_now["rows"]) == 10
|
|
|
|
admin_res = client.post("/api/auth/login", json={"email": "admin@poona.demo", "password": "Demo@123"})
|
|
headers = {"Authorization": f"Bearer {admin_res.json()['access_token']}"}
|
|
try:
|
|
future_date = today + timedelta(days=365 * 2)
|
|
client.post("/api/settings/demo-date", headers=headers, json={"demo_as_of_date": str(future_date)})
|
|
ds_future = load_ai_dataset(db, admin, future_date - timedelta(days=365), future_date)
|
|
dep_future = compute_depreciation_from_dataset(ds_future)
|
|
assert dep_future["summary"]["total_book_value"] < dep_now["summary"]["total_book_value"]
|
|
finally:
|
|
client.post("/api/settings/demo-date", headers=headers, json={"demo_as_of_date": None})
|
|
|