Files
Medasset_ai/backend/tests/test_ai1_cost_inputs.py

449 lines
17 KiB
Python

from datetime import timedelta
from io import BytesIO
import openpyxl
import pytest
from sqlalchemy import create_engine, text
from app.core.migrations import run_sqlite_migrations
from app.core.time_utils import effective_today
from app.models import Asset, Category, Complaint, Contract, PMSchedule, Vendor
from app.seed.seed import seed_database
from app.services.permissions import COST_FIELDS
@pytest.fixture(scope="module", autouse=True)
def seeded_ai1_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("ai1_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 _collect_keys(obj) -> set[str]:
keys: set[str] = set()
if isinstance(obj, dict):
for k, v in obj.items():
keys.add(k)
keys.update(_collect_keys(v))
elif isinstance(obj, list):
for item in obj:
keys.update(_collect_keys(item))
return keys
def test_sqlite_migration_adds_cost_columns_to_old_db(tmp_path):
db_file = tmp_path / "legacy.db"
eng = create_engine(f"sqlite:///{db_file}")
with eng.begin() as conn:
conn.exec_driver_sql(
"""
CREATE TABLE categories (
id INTEGER PRIMARY KEY,
name VARCHAR(150) NOT NULL,
description TEXT,
is_active BOOLEAN NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
)
"""
)
conn.exec_driver_sql(
"""
CREATE TABLE assets (
id INTEGER PRIMARY KEY,
asset_code VARCHAR(60) NOT NULL,
serial_no VARCHAR(100) NOT NULL,
name VARCHAR(200) NOT NULL,
category_id INTEGER NOT NULL,
department_id INTEGER NOT NULL,
location_id INTEGER NOT NULL,
supplier_id INTEGER,
purchase_value FLOAT,
purchase_date DATE,
installation_date DATE,
status VARCHAR(40) NOT NULL,
criticality VARCHAR(30) NOT NULL,
requires_calibration BOOLEAN NOT NULL DEFAULT 0,
insurance_applicable BOOLEAN NOT NULL DEFAULT 0,
remarks TEXT,
created_at DATETIME NOT NULL,
created_by_id INTEGER,
updated_at DATETIME NOT NULL,
updated_by_id INTEGER
)
"""
)
conn.exec_driver_sql(
"""
CREATE TABLE contracts (
id INTEGER PRIMARY KEY,
asset_id INTEGER NOT NULL,
contract_type VARCHAR(20) NOT NULL,
provider_id INTEGER NOT NULL,
start_date DATE NOT NULL,
end_date DATE NOT NULL,
coverage_period_text VARCHAR(100),
renewed_from_id INTEGER,
is_superseded BOOLEAN NOT NULL DEFAULT 0,
remarks TEXT,
created_at DATETIME NOT NULL,
created_by_id INTEGER,
updated_at DATETIME NOT NULL,
updated_by_id INTEGER
)
"""
)
conn.exec_driver_sql(
"""
CREATE TABLE pm_schedules (
id INTEGER PRIMARY KEY,
asset_id INTEGER NOT NULL,
service_mode VARCHAR(30) NOT NULL,
frequency_months INTEGER NOT NULL,
responsible_team VARCHAR(150),
provider_id INTEGER,
contract_id INTEGER,
next_planned_date DATE NOT NULL,
is_active BOOLEAN NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL,
created_by_id INTEGER,
updated_at DATETIME NOT NULL,
updated_by_id INTEGER
)
"""
)
conn.exec_driver_sql(
"""
CREATE TABLE complaints (
id INTEGER PRIMARY KEY,
complaint_no VARCHAR(60) NOT NULL,
asset_id INTEGER NOT NULL,
description TEXT NOT NULL,
priority VARCHAR(30) NOT NULL,
registered_at DATETIME NOT NULL,
registered_by_id INTEGER NOT NULL,
received_by_id INTEGER NOT NULL,
call_status VARCHAR(30) NOT NULL,
spare_required BOOLEAN NOT NULL DEFAULT 0,
updated_at DATETIME NOT NULL
)
"""
)
conn.exec_driver_sql(
"""
INSERT INTO assets (
id, asset_code, serial_no, name, category_id, department_id, location_id,
status, criticality, requires_calibration, insurance_applicable, created_at, updated_at
) VALUES (
1, 'OLD-001', 'SN-1', 'Legacy Monitor', 1, 1, 1,
'in_service', 'critical', 0, 0, '2025-01-01', '2025-01-01'
)
"""
)
run_sqlite_migrations(eng)
with eng.connect() as conn:
asset_cols = {r[1] for r in conn.execute(text("PRAGMA table_info(assets)")).fetchall()}
cat_cols = {r[1] for r in conn.execute(text("PRAGMA table_info(categories)")).fetchall()}
con_cols = {r[1] for r in conn.execute(text("PRAGMA table_info(contracts)")).fetchall()}
pm_cols = {r[1] for r in conn.execute(text("PRAGMA table_info(pm_schedules)")).fetchall()}
cmp_cols = {r[1] for r in conn.execute(text("PRAGMA table_info(complaints)")).fetchall()}
assert {"acquisition_mode", "monthly_rent", "useful_life_years", "salvage_pct", "depreciation_method"}.issubset(asset_cols)
assert "default_useful_life_years" in cat_cols
assert "contract_value" in con_cols
assert "cost_per_visit" in pm_cols
assert "repair_cost" in cmp_cols
mode = conn.execute(text("SELECT acquisition_mode FROM assets WHERE id = 1")).scalar()
assert mode == "purchased"
eng.dispose()
def test_department_user_never_receives_cost_fields(client):
dept_headers = _auth_headers(client, "dept@xyz.demo")
admin_headers = _auth_headers(client, "admin@xyz.demo")
# 1. /api/assets
res_assets = client.get("/api/assets?page_size=20", headers=dept_headers)
assert res_assets.status_code == 200
assert len(res_assets.json()["items"]) > 0
assert not (COST_FIELDS & _collect_keys(res_assets.json()))
first_asset_id = res_assets.json()["items"][0]["id"]
res_asset_one = client.get(f"/api/assets/{first_asset_id}", headers=dept_headers)
assert res_asset_one.status_code == 200
assert not (COST_FIELDS & _collect_keys(res_asset_one.json()))
res_overview = client.get(f"/api/assets/{first_asset_id}/overview", headers=dept_headers)
assert res_overview.status_code == 200
assert not (COST_FIELDS & _collect_keys(res_overview.json()))
# 2. /api/contracts
res_contracts = client.get("/api/contracts?page_size=20", headers=dept_headers)
assert res_contracts.status_code == 200
assert not (COST_FIELDS & _collect_keys(res_contracts.json()))
# 3. /api/complaints
res_complaints = client.get("/api/complaints?page_size=20", headers=dept_headers)
assert res_complaints.status_code == 200
assert len(res_complaints.json()["items"]) > 0
assert not (COST_FIELDS & _collect_keys(res_complaints.json()))
first_comp_id = res_complaints.json()["items"][0]["id"]
res_comp_one = client.get(f"/api/complaints/{first_comp_id}", headers=dept_headers)
assert res_comp_one.status_code == 200
assert not (COST_FIELDS & _collect_keys(res_comp_one.json()))
# 4. /api/pm/schedules
res_pm = client.get("/api/pm/schedules?page_size=20", headers=dept_headers)
assert res_pm.status_code == 200
assert not (COST_FIELDS & _collect_keys(res_pm.json()))
# Admin DOES see cost fields
admin_assets = client.get("/api/assets?page_size=5", headers=admin_headers)
assert "purchase_value" in admin_assets.json()["items"][0]
admin_contracts = client.get("/api/contracts?page_size=5", headers=admin_headers)
assert "contract_value" in admin_contracts.json()["items"][0]
admin_complaints = client.get("/api/complaints?page_size=5", headers=admin_headers)
assert "repair_cost" in admin_complaints.json()["items"][0]
def test_repair_cost_and_cost_editing_role_permissions(client, db):
bio_headers = _auth_headers(client, "bio@xyz.demo")
coord_headers = _auth_headers(client, "coord@xyz.demo")
dept_headers = _auth_headers(client, "dept@xyz.demo")
mgmt_headers = _auth_headers(client, "mgmt@xyz.demo")
# Find an ICU complaint visible to dept@xyz.demo
comp = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.filter(Asset.department_id == 1)
.first()
)
assert comp is not None
# Denied (403) for coordinator, department_user, management
for headers in (coord_headers, dept_headers, mgmt_headers):
res = client.patch(
f"/api/complaints/{comp.id}",
headers=headers,
json={"repair_cost": 9999.0},
)
assert res.status_code == 403, f"Expected 403, got {res.status_code}: {res.text}"
# Allowed for biomedical
res_ok = client.patch(
f"/api/complaints/{comp.id}",
headers=bio_headers,
json={"repair_cost": 14500.0},
)
assert res_ok.status_code == 200, res_ok.text
assert res_ok.json()["repair_cost"] == 14500.0
# Coordinator CAN edit contract_value
contract = db.query(Contract).first()
assert contract is not None
res_con = client.patch(
f"/api/contracts/{contract.id}",
headers=coord_headers,
json={"contract_value": 88000.0},
)
assert res_con.status_code == 200, res_con.text
assert res_con.json()["contract_value"] == 88000.0
# Coordinator CANNOT edit PM cost_per_visit or asset purchase_value
pm_sched = db.query(PMSchedule).filter(PMSchedule.service_mode == "in_house").first()
assert pm_sched is not None
res_pm_deny = client.patch(
f"/api/pm/schedules/{pm_sched.id}",
headers=coord_headers,
json={"cost_per_visit": 9000.0},
)
assert res_pm_deny.status_code == 403
res_asset_deny = client.patch(
f"/api/assets/{comp.asset_id}",
headers=coord_headers,
json={"monthly_rent": 15000.0},
)
assert res_asset_deny.status_code == 403
def test_new_ai_cost_settings_present_and_validated(client):
admin_headers = _auth_headers(client, "admin@xyz.demo")
res = client.get("/api/settings", headers=admin_headers)
assert res.status_code == 200
by_key = {item["key"]: item for item in res.json()["items"]}
expected_defaults = {
"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,
"ai_enabled": True,
}
for key, val in expected_defaults.items():
assert key in by_key, f"Missing setting {key}"
assert by_key[key]["value"] == val
# Invalid range rejected with 422
bad = client.put(
"/api/settings",
headers=admin_headers,
json={"values": {"comparison_horizon_years": 25}},
)
assert bad.status_code == 422
bad_ratio = client.put(
"/api/settings",
headers=admin_headers,
json={"values": {"replacement_review_ratio": 5.0}},
)
assert bad_ratio.status_code == 422
# Valid update succeeds
good = client.put(
"/api/settings",
headers=admin_headers,
json={"values": {"comparison_horizon_years": 7, "replacement_review_ratio": 0.45}},
)
assert good.status_code == 200
# Restore defaults
client.put(
"/api/settings",
headers=admin_headers,
json={"values": {"comparison_horizon_years": 5, "replacement_review_ratio": 0.4}},
)
def test_seed_data_meets_cost_and_ai_prerequisites(db):
today = effective_today(db)
assets = db.query(Asset).all()
contracts = db.query(Contract).all()
inhouse_pms = db.query(PMSchedule).filter(PMSchedule.service_mode == "in_house").all()
closed_complaints = db.query(Complaint).filter(Complaint.call_status == "closed").all()
rented = [a for a in assets if a.acquisition_mode == "rented" and a.monthly_rent is not None]
assert len(rented) == 6
owned_with_rent_quote = [
a for a in assets if a.acquisition_mode == "purchased" and a.monthly_rent is not None
]
assert len(owned_with_rent_quote) >= 25
assert all(c.contract_value is not None and c.contract_value > 0 for c in contracts)
assert all(p.cost_per_visit is not None and p.cost_per_visit > 0 for p in inhouse_pms)
closed_with_repair = [c for c in closed_complaints if c.repair_cost is not None]
assert len(closed_with_repair) >= 12 # ~60% of 22 closed
latest_12m = [
a for a in assets if a.purchase_date is not None and (today - a.purchase_date).days <= 365
]
assert len(latest_12m) >= 10
fully_dep = [
a
for a in assets
if a.acquisition_mode == "purchased"
and (a.installation_date or a.purchase_date) is not None
and ((today - (a.installation_date or a.purchase_date)).days / 365.25)
>= (a.useful_life_years or 10)
]
assert len(fully_dep) >= 1
# At least 3 assets with >= 3 breakdowns in last 90 days
cutoff = today - timedelta(days=90)
counts_by_asset: dict[int, int] = {}
for c in db.query(Complaint).all():
if c.registered_at.date() >= cutoff:
counts_by_asset[c.asset_id] = counts_by_asset.get(c.asset_id, 0) + 1
repeat_assets = [aid for aid, cnt in counts_by_asset.items() if cnt >= 3]
assert len(repeat_assets) >= 3
# At least 2 assets with repair+spare+contract cost > 40% of purchase value
high_maint = 0
for a in assets:
if not a.purchase_value:
continue
comp_cost = sum(
(c.repair_cost or 0.0) + (c.spare_cost_estimate or 0.0)
for c in db.query(Complaint).filter(Complaint.asset_id == a.id).all()
)
if comp_cost / a.purchase_value >= 0.4:
high_maint += 1
assert high_maint >= 2
def test_asset_and_contract_bulk_import_cost_columns(client, db):
admin_headers = _auth_headers(client, "admin@xyz.demo")
cat = db.query(Category).first()
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
# Import an asset with new cost/depreciation columns
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Assets"
ws.append([
"asset_code", "serial_no", "name", "category", "department", "location",
"purchase_value", "acquisition_mode", "monthly_rent", "useful_life_years",
"salvage_pct", "depreciation_method",
])
ws.append([
"PHRC-AI1-0001", "SN-AI1-01", "Test Cost Monitor", cat.name, "ICU", "ICU Bay A",
500000, "purchased", 14000, 8, 10, "written_down",
])
buf = BytesIO()
wb.save(buf)
res = client.post(
"/api/assets/bulk-import?dry_run=false",
headers=admin_headers,
files={"file": ("assets_cost.xlsx", buf.getvalue(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
)
assert res.status_code == 200, res.text
assert res.json()["created_count"] == 1
created = db.query(Asset).filter(Asset.asset_code == "PHRC-AI1-0001").first()
assert created is not None
assert created.acquisition_mode == "purchased"
assert created.monthly_rent == 14000.0
assert created.useful_life_years == 8
assert created.salvage_pct == 10.0
assert created.depreciation_method == "written_down"
# Import contract with contract_value
wb2 = openpyxl.Workbook()
ws2 = wb2.active
ws2.title = "Contracts"
ws2.append(["asset_code", "provider_name", "contract_type", "start_date", "end_date", "contract_value"])
ws2.append(["PHRC-AI1-0001", vendor.name, "AMC", "2026-01-01", "2026-12-31", 42500])
buf2 = BytesIO()
wb2.save(buf2)
res2 = client.post(
"/api/contracts/bulk-import?dry_run=false",
headers=admin_headers,
files={"file": ("contracts_cost.xlsx", buf2.getvalue(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
)
assert res2.status_code == 200, res2.text
assert res2.json()["created_count"] == 1
con = db.query(Contract).filter(Contract.asset_id == created.id).first()
assert con is not None
assert con.contract_value == 42500.0