initial commit
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
import asyncio
|
||||
import threading
|
||||
import httpx
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.core.db import get_db
|
||||
from app.main import app
|
||||
from app.models import Base
|
||||
from app.routers.auth import reset_login_rate_limiter
|
||||
|
||||
SQLALCHEMY_TEST_URL = "sqlite:///./data/test.db"
|
||||
engine_test = create_engine(SQLALCHEMY_TEST_URL, connect_args={"check_same_thread": False})
|
||||
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine_test)
|
||||
|
||||
|
||||
class _WaitSelector:
|
||||
def __init__(self, event: threading.Event):
|
||||
self._event = event
|
||||
|
||||
def select(self, timeout=None):
|
||||
self._event.wait(timeout)
|
||||
self._event.clear()
|
||||
return []
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class _SocketFreeEventLoop(asyncio.BaseEventLoop):
|
||||
"""Pure-Python asyncio loop using threading.Event instead of socketpair (works in Windows sandbox)."""
|
||||
|
||||
def __init__(self):
|
||||
self._wake_event = threading.Event()
|
||||
super().__init__()
|
||||
self._selector = _WaitSelector(self._wake_event)
|
||||
|
||||
def _write_to_self(self):
|
||||
self._wake_event.set()
|
||||
|
||||
def _process_events(self, event_list):
|
||||
pass
|
||||
|
||||
def _close_self_pipe(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
super().close()
|
||||
self._selector.close()
|
||||
|
||||
|
||||
class SyncASGITestClient:
|
||||
"""Synchronous HTTP test client backed by httpx.AsyncClient + ASGITransport."""
|
||||
|
||||
def __init__(self, asgi_app):
|
||||
self._app = asgi_app
|
||||
self._loop = _SocketFreeEventLoop()
|
||||
self._lifespan_cm = asgi_app.router.lifespan_context(asgi_app)
|
||||
self._loop.run_until_complete(self._lifespan_cm.__aenter__())
|
||||
self._client = httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=asgi_app),
|
||||
base_url="http://testserver",
|
||||
)
|
||||
|
||||
def request(self, method: str, url: str, **kwargs) -> httpx.Response:
|
||||
return self._loop.run_until_complete(self._client.request(method, url, **kwargs))
|
||||
|
||||
def get(self, url: str, **kwargs) -> httpx.Response:
|
||||
return self.request("GET", url, **kwargs)
|
||||
|
||||
def post(self, url: str, **kwargs) -> httpx.Response:
|
||||
return self.request("POST", url, **kwargs)
|
||||
|
||||
def put(self, url: str, **kwargs) -> httpx.Response:
|
||||
return self.request("PUT", url, **kwargs)
|
||||
|
||||
def patch(self, url: str, **kwargs) -> httpx.Response:
|
||||
return self.request("PATCH", url, **kwargs)
|
||||
|
||||
def delete(self, url: str, **kwargs) -> httpx.Response:
|
||||
return self.request("DELETE", url, **kwargs)
|
||||
|
||||
def close(self):
|
||||
self._loop.run_until_complete(self._client.aclose())
|
||||
self._loop.run_until_complete(self._lifespan_cm.__aexit__(None, None, None))
|
||||
self._loop.close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def db():
|
||||
Base.metadata.drop_all(bind=engine_test)
|
||||
Base.metadata.create_all(bind=engine_test)
|
||||
session = TestingSessionLocal()
|
||||
yield session
|
||||
session.close()
|
||||
Base.metadata.drop_all(bind=engine_test)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client(db):
|
||||
def override_get_db():
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
pass
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
c = SyncASGITestClient(app)
|
||||
try:
|
||||
yield c
|
||||
finally:
|
||||
c.close()
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_login_rate_limiter():
|
||||
reset_login_rate_limiter()
|
||||
yield
|
||||
reset_login_rate_limiter()
|
||||
@@ -0,0 +1,448 @@
|
||||
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@poona.demo")
|
||||
admin_headers = _auth_headers(client, "admin@poona.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@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
|
||||
# Find an ICU complaint visible to dept@poona.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@poona.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@poona.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
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
from datetime import date, timedelta
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import Asset, Category, ComplaintEvent, Contract, Department, Location, Vendor, Warranty
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.coverage import get_coverage
|
||||
from app.services.permissions import COST_FIELDS
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_ai2_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("ai2_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 _create_isolated_asset(db, code: str, dept_code: str = "ICU") -> Asset:
|
||||
dept = db.query(Department).filter(Department.code == dept_code).first()
|
||||
loc = db.query(Location).filter(Location.department_id == dept.id).first()
|
||||
cat = db.query(Category).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
asset = Asset(
|
||||
asset_code=code,
|
||||
serial_no=f"SN-{code}",
|
||||
name=f"Coverage Test Asset {code}",
|
||||
category_id=cat.id,
|
||||
department_id=dept.id,
|
||||
location_id=loc.id,
|
||||
supplier_id=vendor.id,
|
||||
purchase_value=500000.0,
|
||||
status="in_service",
|
||||
criticality="critical",
|
||||
)
|
||||
db.add(asset)
|
||||
db.commit()
|
||||
db.refresh(asset)
|
||||
return asset
|
||||
|
||||
|
||||
def test_coverage_priority_and_expiry_boundaries_and_superseded(db):
|
||||
asset = _create_isolated_asset(db, "PHRC-COV-0001")
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).limit(4).all()
|
||||
on_d = date(2026, 6, 15)
|
||||
|
||||
# 1. No coverage -> out_of_contract (severity red)
|
||||
cov0 = get_coverage(db, asset.id, on_d)
|
||||
assert cov0["tag"] == "out_of_contract"
|
||||
assert cov0["severity"] == "red"
|
||||
assert cov0["provider_id"] is None
|
||||
|
||||
# 2. Add superseded CMC covering on_d -> must be ignored!
|
||||
sup_cmc = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type="CMC",
|
||||
provider_id=vendors[0].id,
|
||||
start_date=date(2026, 1, 1),
|
||||
end_date=date(2026, 12, 31),
|
||||
is_superseded=True,
|
||||
)
|
||||
db.add(sup_cmc)
|
||||
db.commit()
|
||||
assert get_coverage(db, asset.id, on_d)["tag"] == "out_of_contract"
|
||||
|
||||
# 3. Add active OTHER contract -> tag = other_contract
|
||||
other_c = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type="OTHER",
|
||||
provider_id=vendors[0].id,
|
||||
start_date=date(2026, 6, 1),
|
||||
end_date=date(2026, 6, 30),
|
||||
is_superseded=False,
|
||||
)
|
||||
db.add(other_c)
|
||||
db.commit()
|
||||
cov_other = get_coverage(db, asset.id, on_d)
|
||||
assert cov_other["tag"] == "other_contract"
|
||||
assert cov_other["contract_id"] == other_c.id
|
||||
assert cov_other["days_left"] == 15
|
||||
assert cov_other["severity"] == "yellow" # within 30d lead, > 7d red
|
||||
|
||||
# Boundary dates: start_date and end_date are inclusive; day before/after are out_of_contract
|
||||
assert get_coverage(db, asset.id, date(2026, 5, 31))["tag"] == "out_of_contract"
|
||||
assert get_coverage(db, asset.id, date(2026, 6, 1))["tag"] == "other_contract"
|
||||
assert get_coverage(db, asset.id, date(2026, 6, 30))["tag"] == "other_contract"
|
||||
assert get_coverage(db, asset.id, date(2026, 6, 30))["days_left"] == 0
|
||||
assert get_coverage(db, asset.id, date(2026, 6, 30))["severity"] == "red"
|
||||
assert get_coverage(db, asset.id, date(2026, 7, 1))["tag"] == "out_of_contract"
|
||||
|
||||
# 4. Add active AMC -> beats OTHER
|
||||
amc_c = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type="AMC",
|
||||
provider_id=vendors[1].id,
|
||||
start_date=date(2026, 1, 1),
|
||||
end_date=date(2026, 12, 31),
|
||||
is_superseded=False,
|
||||
)
|
||||
db.add(amc_c)
|
||||
db.commit()
|
||||
cov_amc = get_coverage(db, asset.id, on_d)
|
||||
assert cov_amc["tag"] == "amc"
|
||||
assert cov_amc["contract_id"] == amc_c.id
|
||||
assert cov_amc["severity"] == "ok"
|
||||
|
||||
# 5. Add active CMC -> beats AMC
|
||||
cmc_c = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type="CMC",
|
||||
provider_id=vendors[2].id,
|
||||
start_date=date(2026, 1, 1),
|
||||
end_date=date(2026, 12, 31),
|
||||
is_superseded=False,
|
||||
)
|
||||
db.add(cmc_c)
|
||||
db.commit()
|
||||
cov_cmc = get_coverage(db, asset.id, on_d)
|
||||
assert cov_cmc["tag"] == "cmc"
|
||||
assert cov_cmc["contract_id"] == cmc_c.id
|
||||
|
||||
# 6. Add active Warranty -> beats CMC
|
||||
warr = Warranty(
|
||||
asset_id=asset.id,
|
||||
duration_months=12,
|
||||
start_date=date(2026, 1, 1),
|
||||
end_date=date(2026, 12, 31),
|
||||
provider_id=vendors[3].id,
|
||||
)
|
||||
db.add(warr)
|
||||
db.commit()
|
||||
cov_warr = get_coverage(db, asset.id, on_d)
|
||||
assert cov_warr["tag"] == "warranty"
|
||||
assert cov_warr["warranty_id"] == warr.id
|
||||
assert cov_warr["provider_name"] == vendors[3].name
|
||||
assert cov_warr["provider_contact"] is not None
|
||||
|
||||
|
||||
def test_complaint_coverage_snapshot_persists_after_contract_expires(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
asset = _create_isolated_asset(db, "PHRC-COV-0002")
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
today = effective_today(db)
|
||||
|
||||
# Create active AMC ending in 10 days
|
||||
amc = Contract(
|
||||
asset_id=asset.id,
|
||||
contract_type="AMC",
|
||||
provider_id=vendor.id,
|
||||
start_date=today - timedelta(days=30),
|
||||
end_date=today + timedelta(days=10),
|
||||
contract_value=50000.0,
|
||||
is_superseded=False,
|
||||
)
|
||||
db.add(amc)
|
||||
db.commit()
|
||||
|
||||
# Raise complaint while AMC is active
|
||||
create_res = client.post(
|
||||
"/api/complaints",
|
||||
headers=admin_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"description": "Power supply intermittent",
|
||||
"priority": "critical",
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
comp = create_res.json()
|
||||
cid = comp["id"]
|
||||
assert comp["coverage_tag"] == "amc"
|
||||
assert comp["coverage_at_registration"]["tag"] == "amc"
|
||||
assert comp["coverage_now"]["tag"] == "amc"
|
||||
|
||||
# Verify 'coverage_tagged' event was created
|
||||
events = db.query(ComplaintEvent).filter(ComplaintEvent.complaint_id == cid).all()
|
||||
assert any(ev.event_type == "coverage_tagged" and ev.to_value == "amc" for ev in events)
|
||||
|
||||
# Filter GET /api/complaints?coverage_tag=amc includes this complaint
|
||||
filt_res = client.get(f"/api/complaints?coverage_tag=amc&asset_id={asset.id}", headers=admin_headers)
|
||||
assert filt_res.status_code == 200
|
||||
assert any(item["id"] == cid for item in filt_res.json()["items"])
|
||||
|
||||
# Advance demo clock past contract end_date (+20 days)
|
||||
future = today + timedelta(days=20)
|
||||
try:
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": str(future)},
|
||||
)
|
||||
after_res = client.get(f"/api/complaints/{cid}", headers=admin_headers)
|
||||
assert after_res.status_code == 200
|
||||
after_data = after_res.json()
|
||||
# Snapshot at registration remains 'amc', while coverage_now flips to 'out_of_contract'
|
||||
assert after_data["coverage_at_registration"]["tag"] == "amc"
|
||||
assert after_data["coverage_now"]["tag"] == "out_of_contract"
|
||||
finally:
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": None},
|
||||
)
|
||||
|
||||
# Verify Breakdown/Complaint report and Excel export include Coverage column
|
||||
rep_res = client.get("/api/reports/breakdown-complaints", headers=admin_headers)
|
||||
assert rep_res.status_code == 200
|
||||
col_labels = [c["label"] for c in rep_res.json()["columns"]]
|
||||
assert "Coverage" in col_labels
|
||||
|
||||
exp_res = client.get("/api/reports/breakdown-complaints/export?format=xlsx", headers=admin_headers)
|
||||
assert exp_res.status_code == 200
|
||||
wb = openpyxl.load_workbook(BytesIO(exp_res.content))
|
||||
ws = wb.active
|
||||
all_cells = [cell.value for row in ws.iter_rows(min_row=1, max_row=15) for cell in row]
|
||||
assert "Coverage" in all_cells
|
||||
|
||||
|
||||
def test_pm_outsourced_auto_fill_and_no_active_contract_warning(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
today = effective_today(db)
|
||||
|
||||
# Case 1: Asset with active CMC -> auto-fills contract_id and provider_id
|
||||
asset_with_cmc = _create_isolated_asset(db, "PHRC-COV-PM1")
|
||||
cmc = Contract(
|
||||
asset_id=asset_with_cmc.id,
|
||||
contract_type="CMC",
|
||||
provider_id=vendor.id,
|
||||
start_date=today - timedelta(days=10),
|
||||
end_date=today + timedelta(days=300),
|
||||
is_superseded=False,
|
||||
)
|
||||
db.add(cmc)
|
||||
db.commit()
|
||||
|
||||
res_auto = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset_with_cmc.id,
|
||||
"service_mode": "outsourced",
|
||||
"frequency_months": 6,
|
||||
"next_planned_date": str(today + timedelta(days=30)),
|
||||
},
|
||||
)
|
||||
assert res_auto.status_code == 201, res_auto.text
|
||||
auto_data = res_auto.json()
|
||||
assert auto_data["contract_id"] == cmc.id
|
||||
assert auto_data["provider_id"] == vendor.id
|
||||
assert auto_data["coverage_tag"] == "cmc"
|
||||
assert not auto_data.get("no_active_contract")
|
||||
|
||||
# Case 2: Asset with NO active AMC/CMC -> leaves empty & returns no_active_contract=True
|
||||
asset_no_con = _create_isolated_asset(db, "PHRC-COV-PM2")
|
||||
res_warn = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset_no_con.id,
|
||||
"service_mode": "outsourced",
|
||||
"frequency_months": 6,
|
||||
"next_planned_date": str(today + timedelta(days=30)),
|
||||
},
|
||||
)
|
||||
assert res_warn.status_code == 201, res_warn.text
|
||||
warn_data = res_warn.json()
|
||||
assert warn_data["contract_id"] is None
|
||||
assert warn_data["provider_id"] is None
|
||||
assert warn_data["no_active_contract"] is True
|
||||
assert warn_data["coverage_tag"] == "out_of_contract"
|
||||
|
||||
|
||||
def test_department_user_reads_coverage_tag_without_cost_fields(client, db):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
icu_asset = db.query(Asset).filter(Asset.department_id == 1).first()
|
||||
assert icu_asset is not None
|
||||
|
||||
# GET /api/assets/{id}/coverage succeeds for department_user's own department
|
||||
cov_res = client.get(f"/api/assets/{icu_asset.id}/coverage", headers=dept_headers)
|
||||
assert cov_res.status_code == 200
|
||||
cov_data = cov_res.json()
|
||||
assert cov_data["tag"] in ("warranty", "cmc", "amc", "other_contract", "out_of_contract")
|
||||
assert not (COST_FIELDS & set(cov_data.keys()))
|
||||
|
||||
# GET /api/assets/{id}/overview includes coverage tag but zero cost fields
|
||||
ov_res = client.get(f"/api/assets/{icu_asset.id}/overview", headers=dept_headers)
|
||||
assert ov_res.status_code == 200
|
||||
ov_data = ov_res.json()
|
||||
assert ov_data["coverage"]["tag"] == cov_data["tag"]
|
||||
assert "purchase_value" not in ov_data["asset"]
|
||||
assert "monthly_rent" not in ov_data["asset"]
|
||||
|
||||
# Another department's asset coverage is 403 for department_user
|
||||
other_asset = db.query(Asset).filter(Asset.department_id != 1).first()
|
||||
assert other_asset is not None
|
||||
forbid = client.get(f"/api/assets/{other_asset.id}/coverage", headers=dept_headers)
|
||||
assert forbid.status_code == 403
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
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})
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import re
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import User
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.ai_metrics import DEFAULT_AI_SETTINGS, load_ai_dataset
|
||||
from app.services.ai_suggestions import SEVERITY_RANK, generate_suggestions
|
||||
|
||||
BANNED_WORDS_RE = re.compile(
|
||||
r"\b(approve|approved|guarantee|safe to use|safe|unsafe|purchase immediately|must buy)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _base_dataset(today: date, assets: list[dict], **overrides) -> dict:
|
||||
ds = {
|
||||
"today": today,
|
||||
"now_utc": datetime(today.year, today.month, today.day, 12, 0, tzinfo=timezone.utc),
|
||||
"period_start": today - timedelta(days=90),
|
||||
"period_end": today,
|
||||
"settings": dict(DEFAULT_AI_SETTINGS),
|
||||
"assets": assets,
|
||||
"contracts_by_asset": {},
|
||||
"complaints": [],
|
||||
"complaints_by_asset": {},
|
||||
"pm_schedules_by_asset": {},
|
||||
"pm_records": [],
|
||||
"pm_records_by_asset": {},
|
||||
"coverage_by_asset": {},
|
||||
"cal_plans_by_asset": {},
|
||||
"cal_records_by_asset": {},
|
||||
}
|
||||
ds.update(overrides)
|
||||
return ds
|
||||
|
||||
|
||||
def _assert_suggestion_invariants(res: dict):
|
||||
ev_ids = {m["id"] for m in res["evidence"]}
|
||||
suggestions = res["suggestions"]
|
||||
# Every referenced evidence_metric_id must exist
|
||||
for s in suggestions:
|
||||
assert s["action_for_human"].endswith("Needs a human decision.")
|
||||
assert len(s["evidence_metric_ids"]) > 0
|
||||
for mid in s["evidence_metric_ids"]:
|
||||
assert mid in ev_ids, f"Missing evidence metric id {mid} for suggestion {s['id']}"
|
||||
for field in (s["title"], s["detail"], s["action_for_human"]):
|
||||
assert not BANNED_WORDS_RE.search(field), f"Banned word found in {field!r}"
|
||||
|
||||
# Verify strict ordering: red -> yellow -> info, then asset_code, then rule
|
||||
keys = [
|
||||
(SEVERITY_RANK[s["severity"]], s["asset_codes"][0] if s["asset_codes"] else "", s["rule"])
|
||||
for s in suggestions
|
||||
]
|
||||
assert keys == sorted(keys)
|
||||
|
||||
|
||||
def test_rule_s1_repeat_failure_yellow_and_red():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-YEL", "name": "Vent Yellow", "department_name": "ICU", "category_name": "Life Support", "status": "in_service"},
|
||||
{"id": 2, "asset_code": "A-RED", "name": "Vent Red", "department_name": "ICU", "category_name": "Life Support", "status": "in_service"},
|
||||
]
|
||||
cmps_1 = [
|
||||
{"id": i, "asset_id": 1, "priority": "non_critical", "registered_at": datetime(2026, 5, i + 1, 10, 0, tzinfo=timezone.utc)}
|
||||
for i in range(3)
|
||||
]
|
||||
cmps_2 = [
|
||||
{"id": 10 + i, "asset_id": 2, "priority": "critical", "registered_at": datetime(2026, 5, i + 1, 10, 0, tzinfo=timezone.utc)}
|
||||
for i in range(4)
|
||||
]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps_1 + cmps_2,
|
||||
complaints_by_asset={1: cmps_1, 2: cmps_2},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 100}, 2: {"tag": "cmc", "days_left": 100}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s1_map = {s["asset_codes"][0]: s for s in res["suggestions"] if s["rule"] == "S1"}
|
||||
assert s1_map["A-YEL"]["severity"] == "yellow"
|
||||
assert s1_map["A-RED"]["severity"] == "red"
|
||||
assert "Review root cause and escalate to the vendor" in s1_map["A-RED"]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s2_out_of_contract_with_two_breakdowns():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-OOC", "name": "Monitor", "department_name": "ICU", "category_name": "Monitors", "status": "in_service"},
|
||||
]
|
||||
cmps = [
|
||||
{"id": 1, "asset_id": 1, "priority": "non_critical", "registered_at": datetime(2026, 5, 5, 10, 0, tzinfo=timezone.utc)},
|
||||
{"id": 2, "asset_id": 1, "priority": "non_critical", "registered_at": datetime(2026, 5, 20, 10, 0, tzinfo=timezone.utc)},
|
||||
]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps,
|
||||
complaints_by_asset={1: cmps},
|
||||
coverage_by_asset={1: {"tag": "out_of_contract", "days_left": None}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s2 = [s for s in res["suggestions"] if s["rule"] == "S2"]
|
||||
assert len(s2) == 1
|
||||
assert s2[0]["severity"] == "yellow"
|
||||
assert "Consider an AMC/CMC" in s2[0]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s3_expiring_contract_with_breakdown():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-EXP", "name": "Pump", "department_name": "ICU", "category_name": "Infusion", "status": "in_service"},
|
||||
]
|
||||
cmps = [
|
||||
{"id": 1, "asset_id": 1, "priority": "non_critical", "registered_at": datetime(2026, 6, 1, 10, 0, tzinfo=timezone.utc)},
|
||||
]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps,
|
||||
complaints_by_asset={1: cmps},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 12}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s3 = [s for s in res["suggestions"] if s["rule"] == "S3"]
|
||||
assert len(s3) == 1
|
||||
assert s3[0]["severity"] == "yellow"
|
||||
assert "Renewal review before expiry" in s3[0]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s4_high_maintenance_ratio_yellow_and_red():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-M50", "name": "Pump 50%", "department_name": "ICU", "category_name": "Infusion", "status": "in_service", "purchase_value": 100_000.0, "installation_date": date(2023, 1, 1)},
|
||||
{"id": 2, "asset_code": "A-M120", "name": "Pump 120%", "department_name": "ICU", "category_name": "Infusion", "status": "in_service", "purchase_value": 100_000.0, "installation_date": date(2023, 1, 1)},
|
||||
]
|
||||
cmps_1 = [{"id": 1, "asset_id": 1, "registered_at": datetime(2026, 4, 1, tzinfo=timezone.utc), "repair_cost": 55_000.0, "spare_cost_estimate": 0.0}]
|
||||
cmps_2 = [{"id": 2, "asset_id": 2, "registered_at": datetime(2026, 4, 1, tzinfo=timezone.utc), "repair_cost": 120_000.0, "spare_cost_estimate": 0.0}]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps_1 + cmps_2,
|
||||
complaints_by_asset={1: cmps_1, 2: cmps_2},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 100}, 2: {"tag": "amc", "days_left": 100}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s4_map = {s["asset_codes"][0]: s for s in res["suggestions"] if s["rule"] == "S4"}
|
||||
assert s4_map["A-M50"]["severity"] == "yellow"
|
||||
assert s4_map["A-M120"]["severity"] == "red"
|
||||
assert "Replacement review" in s4_map["A-M120"]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s5_cheaper_scenario_by_10_percent_info():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{
|
||||
"id": 1,
|
||||
"asset_code": "A-S5",
|
||||
"name": "Monitor S5",
|
||||
"department_name": "ICU",
|
||||
"category_name": "Monitors",
|
||||
"status": "in_service",
|
||||
"acquisition_mode": "purchased",
|
||||
"purchase_value": 1_000_000.0,
|
||||
"monthly_rent": 5_000.0, # 5y rent = 300,000 vs in-house >= 475,000 -> >10% cheaper!
|
||||
"useful_life_years": 10,
|
||||
"salvage_pct": 5.0,
|
||||
"depreciation_method": "straight_line",
|
||||
"installation_date": date(2025, 6, 1),
|
||||
}
|
||||
]
|
||||
pm_scheds = {1: [{"id": 1, "asset_id": 1, "service_mode": "in_house", "frequency_months": 6, "cost_per_visit": 10_000.0, "is_active": True}]}
|
||||
ds = _base_dataset(today, assets, pm_schedules_by_asset=pm_scheds, coverage_by_asset={1: {"tag": "warranty", "days_left": 100}})
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s5 = [s for s in res["suggestions"] if s["rule"] == "S5"]
|
||||
assert len(s5) == 1
|
||||
assert s5[0]["severity"] == "info"
|
||||
assert "Evaluate Rent" in s5[0]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s6_pm_overdue_with_breakdown():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [{"id": 1, "asset_code": "A-PMO", "name": "Autoclave", "department_name": "OT", "category_name": "CSSD", "status": "in_service"}]
|
||||
cmps = [{"id": 1, "asset_id": 1, "registered_at": datetime(2026, 6, 1, tzinfo=timezone.utc)}]
|
||||
pm_recs = [{"id": 1, "asset_id": 1, "schedule_id": 1, "planned_date": date(2026, 6, 1), "completed_date": None, "status": None}]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps,
|
||||
complaints_by_asset={1: cmps},
|
||||
pm_records=pm_recs,
|
||||
pm_records_by_asset={1: pm_recs},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 100}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s6 = [s for s in res["suggestions"] if s["rule"] == "S6"]
|
||||
assert len(s6) == 1
|
||||
assert s6[0]["severity"] == "yellow"
|
||||
assert "Clear overdue PM" in s6[0]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s7_calibration_overdue_yellow_and_red():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{"id": 1, "asset_code": "A-CAL-Y", "name": "Cal 10d", "department_name": "LAB", "category_name": "Lab", "status": "in_service"},
|
||||
{"id": 2, "asset_code": "A-CAL-R", "name": "Cal 45d", "department_name": "LAB", "category_name": "Lab", "status": "in_service"},
|
||||
]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
cal_records_by_asset={
|
||||
1: [{"id": 1, "asset_id": 1, "due_date": today - timedelta(days=10), "status": None}],
|
||||
2: [{"id": 2, "asset_id": 2, "due_date": today - timedelta(days=45), "status": None}],
|
||||
},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 100}, 2: {"tag": "amc", "days_left": 100}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s7_map = {s["asset_codes"][0]: s for s in res["suggestions"] if s["rule"] == "S7"}
|
||||
assert s7_map["A-CAL-Y"]["severity"] == "yellow"
|
||||
assert s7_map["A-CAL-R"]["severity"] == "red"
|
||||
assert "Complete calibration" in s7_map["A-CAL-R"]["action_for_human"]
|
||||
|
||||
|
||||
def test_rule_s8_fully_depreciated_and_low_efficiency():
|
||||
today = date(2026, 6, 15)
|
||||
assets = [
|
||||
{
|
||||
"id": 1,
|
||||
"asset_code": "A-OLD",
|
||||
"name": "Old Analyzer",
|
||||
"department_name": "LAB",
|
||||
"category_name": "Lab",
|
||||
"status": "in_service",
|
||||
"purchase_value": 500_000.0,
|
||||
"useful_life_years": 10,
|
||||
"salvage_pct": 5.0,
|
||||
"installation_date": date(2014, 1, 1),
|
||||
}
|
||||
]
|
||||
# 30 days of downtime in 90-day period + 1 overdue PM + slow response -> efficiency well below 80
|
||||
reg = datetime(2026, 5, 1, 10, 0, tzinfo=timezone.utc)
|
||||
cmps = [
|
||||
{
|
||||
"id": 1,
|
||||
"asset_id": 1,
|
||||
"priority": "critical",
|
||||
"registered_at": reg,
|
||||
"attended_at": reg + timedelta(hours=20),
|
||||
"restored_at": reg + timedelta(days=30),
|
||||
"closed_at": reg + timedelta(days=30),
|
||||
}
|
||||
]
|
||||
pm_recs = [{"id": 1, "asset_id": 1, "schedule_id": 1, "planned_date": date(2026, 5, 10), "completed_date": None, "status": None}]
|
||||
ds = _base_dataset(
|
||||
today,
|
||||
assets,
|
||||
complaints=cmps,
|
||||
complaints_by_asset={1: cmps},
|
||||
pm_records=pm_recs,
|
||||
pm_records_by_asset={1: pm_recs},
|
||||
coverage_by_asset={1: {"tag": "amc", "days_left": 100}},
|
||||
)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
s8 = [s for s in res["suggestions"] if s["rule"] == "S8"]
|
||||
assert len(s8) == 1
|
||||
assert s8[0]["severity"] == "yellow"
|
||||
assert "Replacement planning" in s8[0]["action_for_human"]
|
||||
|
||||
|
||||
def test_seeded_db_produces_expected_suggestions(db, tmp_path):
|
||||
seed_database(db, upload_dir=tmp_path)
|
||||
admin = db.query(User).filter(User.email == "admin@poona.demo").first()
|
||||
today = effective_today(db)
|
||||
ds = load_ai_dataset(db, admin, today - timedelta(days=365), today)
|
||||
res = generate_suggestions(ds)
|
||||
_assert_suggestion_invariants(res)
|
||||
|
||||
s1_list = [s for s in res["suggestions"] if s["rule"] == "S1"]
|
||||
s4_list = [s for s in res["suggestions"] if s["rule"] == "S4"]
|
||||
assert len(s1_list) >= 3
|
||||
assert len(s4_list) >= 2
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
import json
|
||||
import httpx
|
||||
|
||||
from app.models import AISummary, AuditLog
|
||||
from app.services.ai_metrics import make_metric
|
||||
from app.services.ai_narrative import (
|
||||
build_prompt,
|
||||
get_or_generate_narrative,
|
||||
rule_based_narrative,
|
||||
validate_narrative,
|
||||
)
|
||||
from app.services.ai_provider import AIProvider, NoneProvider, ProviderUnavailable
|
||||
|
||||
|
||||
class FakeProvider(AIProvider):
|
||||
provider_name = "ollama"
|
||||
model_name = "fake-llama3"
|
||||
|
||||
def __init__(self, responses):
|
||||
# responses: list of dicts or Exceptions or callables
|
||||
self._responses = list(responses)
|
||||
self.calls: list[tuple[str, dict]] = []
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict) -> dict:
|
||||
self.calls.append((system_prompt, user_json))
|
||||
idx = min(len(self.calls) - 1, len(self._responses) - 1)
|
||||
item = self._responses[idx]
|
||||
if isinstance(item, Exception):
|
||||
raise item
|
||||
if callable(item):
|
||||
return item(system_prompt, user_json)
|
||||
return item
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _sample_metrics():
|
||||
return [
|
||||
make_metric("m_cmp_horizon_years", "Comparison Horizon", 5, "years", "5 years"),
|
||||
make_metric("m_cmp_latest_count", "Latest Equipment Evaluated", 10, "count"),
|
||||
make_metric("m_cmp_lowest_PHRC_ICU_0001", "Lowest 5-yr Cost (PHRC-ICU-0001)", 775000.0, "INR"),
|
||||
make_metric("m_cmp_diff_PHRC_ICU_0001", "Savings vs Next Option (PHRC-ICU-0001)", 125000.0, "INR"),
|
||||
make_metric("m_cmp_inhouse_wins", "Equipment Where In-House Is Lowest", 6, "count"),
|
||||
make_metric("m_cmp_outsourced_wins", "Equipment Where Outsourced Is Lowest", 3, "count"),
|
||||
make_metric("m_cmp_rent_wins", "Equipment Where Rent Is Lowest", 1, "count"),
|
||||
]
|
||||
|
||||
|
||||
def test_ai5_valid_provider_response_is_accepted(db):
|
||||
metrics = _sample_metrics()
|
||||
provider = FakeProvider(
|
||||
[
|
||||
{
|
||||
"headline": "Across 10 latest equipment items over 5 years, in-house maintenance is lowest for 6 assets.",
|
||||
"bullets": [
|
||||
{
|
||||
"text": "Lowest estimated 5-year cost for PHRC-ICU-0001 is ₹7,75,000, saving ₹1,25,000 against the next option.",
|
||||
"metric_ids": [
|
||||
"m_cmp_horizon_years",
|
||||
"m_cmp_lowest_PHRC_ICU_0001",
|
||||
"m_cmp_diff_PHRC_ICU_0001",
|
||||
],
|
||||
},
|
||||
{
|
||||
"text": "Across the 10 items, 6 favour in-house, 3 favour outsourced, and 1 favours rent.",
|
||||
"metric_ids": [
|
||||
"m_cmp_latest_count",
|
||||
"m_cmp_inhouse_wins",
|
||||
"m_cmp_outsourced_wins",
|
||||
"m_cmp_rent_wins",
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
res = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m"},
|
||||
metrics,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res["source"] == "ai"
|
||||
assert res["model"] == "fake-llama3"
|
||||
assert res["validated"] is True
|
||||
assert res["failure_reason"] is None
|
||||
assert len(res["bullets"]) == 2
|
||||
assert len(provider.calls) == 1
|
||||
|
||||
|
||||
def test_ai5_invented_number_retries_once_and_falls_back(db):
|
||||
metrics = _sample_metrics()
|
||||
bad_response = {
|
||||
"headline": "Evaluation of 10 assets over 5 years.",
|
||||
"bullets": [
|
||||
{
|
||||
# 999999 is NOT in metrics!
|
||||
"text": "Lowest cost for PHRC-ICU-0001 is ₹9,99,999.",
|
||||
"metric_ids": ["m_cmp_lowest_PHRC_ICU_0001"],
|
||||
}
|
||||
],
|
||||
}
|
||||
provider = FakeProvider([bad_response, bad_response])
|
||||
|
||||
res = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "case": "invented"},
|
||||
metrics,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert len(provider.calls) == 2
|
||||
assert "Unverified number" in provider.calls[1][0]
|
||||
assert res["source"] == "rule_based"
|
||||
assert res["validated"] is False
|
||||
assert res["failure_reason"] and "Unverified number" in res["failure_reason"]
|
||||
assert res["headline"]
|
||||
assert len(res["bullets"]) >= 1
|
||||
|
||||
|
||||
def test_ai5_unknown_metric_id_falls_back(db):
|
||||
metrics = _sample_metrics()
|
||||
bad_response = {
|
||||
"headline": "Summary of 10 items.",
|
||||
"bullets": [
|
||||
{
|
||||
"text": "In-house is lowest for 6 assets.",
|
||||
"metric_ids": ["m_does_not_exist"],
|
||||
}
|
||||
],
|
||||
}
|
||||
provider = FakeProvider([bad_response, bad_response])
|
||||
|
||||
res = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "case": "missing_id"},
|
||||
metrics,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert len(provider.calls) == 2
|
||||
assert res["source"] == "rule_based"
|
||||
assert res["validated"] is False
|
||||
assert res["failure_reason"] and "Unknown metric_id" in res["failure_reason"]
|
||||
|
||||
|
||||
def test_ai5_broken_json_and_timeout_fall_back(db):
|
||||
metrics = _sample_metrics()
|
||||
|
||||
broken_provider = FakeProvider(
|
||||
[
|
||||
json.JSONDecodeError("Expecting value", "{bad", 1),
|
||||
json.JSONDecodeError("Expecting value", "{bad", 1),
|
||||
]
|
||||
)
|
||||
res_broken = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "case": "broken_json"},
|
||||
metrics,
|
||||
provider_override=broken_provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res_broken["source"] == "rule_based"
|
||||
assert res_broken["validated"] is False
|
||||
assert res_broken["failure_reason"]
|
||||
|
||||
timeout_provider = FakeProvider(
|
||||
[ProviderUnavailable("Ollama request timed out after 25s.")]
|
||||
)
|
||||
res_timeout = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "case": "timeout"},
|
||||
metrics,
|
||||
provider_override=timeout_provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert len(timeout_provider.calls) == 1
|
||||
assert res_timeout["source"] == "rule_based"
|
||||
assert res_timeout["validated"] is False
|
||||
assert res_timeout["failure_reason"] and "timed out" in res_timeout["failure_reason"]
|
||||
|
||||
# Also verify raw httpx.TimeoutException never crashes
|
||||
raw_timeout_provider = FakeProvider([httpx.TimeoutException("read timeout")])
|
||||
res_raw_to = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "case": "raw_timeout"},
|
||||
metrics,
|
||||
provider_override=raw_timeout_provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res_raw_to["source"] == "rule_based"
|
||||
assert res_raw_to["failure_reason"]
|
||||
|
||||
|
||||
def test_ai5_banned_words_rejected():
|
||||
metrics = _sample_metrics()
|
||||
for phrase in ("approve", "approved", "guarantee", "safe to use", "unsafe", "purchase immediately", "must buy"):
|
||||
ok, reason = validate_narrative(
|
||||
{
|
||||
"headline": f"We {phrase} this equipment after reviewing 10 items.",
|
||||
"bullets": [{"text": "Total 6 in-house.", "metric_ids": ["m_cmp_inhouse_wins"]}],
|
||||
},
|
||||
metrics,
|
||||
)
|
||||
assert not ok, f"Expected banned phrase '{phrase}' to fail validation"
|
||||
assert reason and "Banned phrase" in reason
|
||||
|
||||
|
||||
def test_ai5_cache_hit_invalidation_and_audit_log(db):
|
||||
metrics_v1 = _sample_metrics()
|
||||
valid_v1 = {
|
||||
"headline": "Evaluated 10 items over 5 years.",
|
||||
"bullets": [{"text": "In-house is lowest for 6 assets.", "metric_ids": ["m_cmp_inhouse_wins"]}],
|
||||
}
|
||||
valid_v2 = {
|
||||
"headline": "Evaluated 10 items over 5 years.",
|
||||
"bullets": [{"text": "In-house is lowest for 7 assets.", "metric_ids": ["m_cmp_inhouse_wins"]}],
|
||||
}
|
||||
provider = FakeProvider([valid_v1, valid_v2, valid_v2])
|
||||
|
||||
before_summaries = db.query(AISummary).filter(AISummary.section == "comparison").count()
|
||||
before_audits = db.query(AuditLog).filter(AuditLog.entity_type == "ai_summary").count()
|
||||
|
||||
# First call: generates and caches
|
||||
res1 = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "dept": None, "case": "cache_test"},
|
||||
metrics_v1,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res1["source"] == "ai"
|
||||
assert len(provider.calls) == 1
|
||||
assert db.query(AISummary).filter(AISummary.section == "comparison").count() == before_summaries + 1
|
||||
assert db.query(AuditLog).filter(AuditLog.entity_type == "ai_summary").count() == before_audits + 1
|
||||
|
||||
# Second call with same filters & metrics: cache hit!
|
||||
res2 = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "dept": None, "case": "cache_test"},
|
||||
metrics_v1,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res2 == res1
|
||||
assert len(provider.calls) == 1
|
||||
|
||||
# Third call with changed metric value: cache invalidated!
|
||||
metrics_v2 = [
|
||||
make_metric("m_cmp_inhouse_wins", "Equipment Where In-House Is Lowest", 7, "count")
|
||||
if m["id"] == "m_cmp_inhouse_wins"
|
||||
else m
|
||||
for m in metrics_v1
|
||||
]
|
||||
res3 = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "dept": None, "case": "cache_test"},
|
||||
metrics_v2,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
)
|
||||
assert res3["source"] == "ai"
|
||||
assert len(provider.calls) == 2
|
||||
assert "7 assets" in res3["bullets"][0]["text"]
|
||||
|
||||
# Fourth call with force_regenerate=True: bypasses cache!
|
||||
res4 = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m", "dept": None, "case": "cache_test"},
|
||||
metrics_v2,
|
||||
provider_override=provider,
|
||||
ai_enabled_override=True,
|
||||
force_regenerate=True,
|
||||
)
|
||||
assert res4["source"] == "ai"
|
||||
assert len(provider.calls) == 3
|
||||
|
||||
|
||||
def test_ai5_privacy_no_pii_or_free_text_in_prompt(db):
|
||||
secret_user = "Dr. Rajesh Deshmukh"
|
||||
secret_email = "rajesh.deshmukh@poonahospital.org"
|
||||
secret_desc = "Patient monitor alarm speaker cracked during ICU night shift"
|
||||
secret_remark = "Confidential nurse note about ward staff conflict"
|
||||
|
||||
dirty_metrics = [
|
||||
{
|
||||
**make_metric("m_bf_total_breakdowns", f"Breakdowns ({secret_email})", 12, "count"),
|
||||
"user_name": secret_user,
|
||||
"email": secret_email,
|
||||
"description": secret_desc,
|
||||
"remarks": secret_remark,
|
||||
}
|
||||
]
|
||||
dirty_suggestions = [
|
||||
{
|
||||
"id": "S1_PHRC_ICU_0001",
|
||||
"rule": "S1",
|
||||
"severity": "red",
|
||||
"title": f"Repeat failure reported by {secret_user}",
|
||||
"detail": f"Complaint description: {secret_desc}; remarks: {secret_remark}",
|
||||
"asset_codes": ["PHRC-ICU-0001"],
|
||||
"evidence_metric_ids": ["m_bf_total_breakdowns"],
|
||||
"action_for_human": "Review root cause and escalate to the vendor. Needs a human decision.",
|
||||
"reported_by": secret_user,
|
||||
"email": secret_email,
|
||||
}
|
||||
]
|
||||
|
||||
sys_prompt, user_payload = build_prompt("breakdown_frequency", dirty_metrics, dirty_suggestions)
|
||||
serialized = sys_prompt + "\n" + json.dumps(user_payload, ensure_ascii=False)
|
||||
|
||||
assert secret_user not in serialized
|
||||
assert secret_email not in serialized
|
||||
assert secret_desc not in serialized
|
||||
assert secret_remark not in serialized
|
||||
# Allowed structured fields MUST remain present
|
||||
assert "m_bf_total_breakdowns" in serialized
|
||||
assert "PHRC-ICU-0001" in serialized
|
||||
|
||||
|
||||
def test_ai5_none_provider_and_disabled_setting_use_rule_based(db):
|
||||
metrics = _sample_metrics()
|
||||
res = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
{"period": "12m"},
|
||||
metrics,
|
||||
provider_override=NoneProvider(),
|
||||
ai_enabled_override=False,
|
||||
)
|
||||
assert res["source"] == "rule_based"
|
||||
assert res["model"] is None
|
||||
assert res["validated"] is True
|
||||
assert res["failure_reason"] is None
|
||||
assert res["headline"]
|
||||
assert len(res["bullets"]) >= 1
|
||||
|
||||
# Also verify direct rule_based_narrative works for every section
|
||||
for sec in ("summary", "comparison", "depreciation", "efficiency", "breakdown_frequency"):
|
||||
out = rule_based_narrative(sec, metrics)
|
||||
assert out["headline"]
|
||||
assert isinstance(out["bullets"], list) and len(out["bullets"]) >= 1
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.models import Category, Department
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_ai6_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("ai6_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']}"}
|
||||
|
||||
|
||||
AI_GET_ENDPOINTS = [
|
||||
"/api/ai/status",
|
||||
"/api/ai/summary",
|
||||
"/api/ai/comparison",
|
||||
"/api/ai/depreciation",
|
||||
"/api/ai/efficiency",
|
||||
"/api/ai/breakdown-frequency",
|
||||
"/api/ai/suggestions",
|
||||
]
|
||||
|
||||
AI_EXPORT_SECTIONS = [
|
||||
"summary",
|
||||
"comparison",
|
||||
"depreciation",
|
||||
"efficiency",
|
||||
"breakdown-frequency",
|
||||
]
|
||||
|
||||
|
||||
def test_ai6_role_matrix_department_user_403_and_viewers_200(client):
|
||||
dept_hdr = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
# department_user must get 403 on EVERY /api/ai/* route
|
||||
for url in AI_GET_ENDPOINTS:
|
||||
r = client.get(url, headers=dept_hdr)
|
||||
assert r.status_code == 403, f"Expected 403 for department_user on {url}, got {r.status_code}"
|
||||
|
||||
for sec in AI_EXPORT_SECTIONS:
|
||||
r = client.get(f"/api/ai/{sec}/export?format=xlsx", headers=dept_hdr)
|
||||
assert r.status_code == 403
|
||||
r_csv = client.get(f"/api/ai/{sec}/export?format=csv", headers=dept_hdr)
|
||||
assert r_csv.status_code == 403
|
||||
|
||||
r_regen_dept = client.post(
|
||||
"/api/ai/narrative/regenerate",
|
||||
json={"section": "summary", "filters": {"period": "12m"}},
|
||||
headers=dept_hdr,
|
||||
)
|
||||
assert r_regen_dept.status_code == 403
|
||||
|
||||
# management, coordinator, biomedical get 200 on all GETs, 403 on regenerate
|
||||
for email in (
|
||||
"mgmt@poona.demo",
|
||||
"coord@poona.demo",
|
||||
"bio@poona.demo",
|
||||
):
|
||||
hdr = _auth_headers(client, email)
|
||||
for url in AI_GET_ENDPOINTS:
|
||||
r = client.get(url, headers=hdr)
|
||||
assert r.status_code == 200, f"Expected 200 for {email} on {url}, got {r.status_code}: {r.text}"
|
||||
r_regen = client.post(
|
||||
"/api/ai/narrative/regenerate",
|
||||
json={"section": "comparison", "filters": {"period": "12m"}},
|
||||
headers=hdr,
|
||||
)
|
||||
assert r_regen.status_code == 403, f"Expected 403 for {email} on regenerate"
|
||||
|
||||
# system_admin gets 200 on all GETs AND 200 on regenerate
|
||||
admin_hdr = _auth_headers(client, "admin@poona.demo")
|
||||
for url in AI_GET_ENDPOINTS:
|
||||
r = client.get(url, headers=admin_hdr)
|
||||
assert r.status_code == 200, f"Expected 200 for admin on {url}: {r.text}"
|
||||
|
||||
r_regen_admin = client.post(
|
||||
"/api/ai/narrative/regenerate",
|
||||
json={"section": "comparison", "filters": {"period": "12m"}},
|
||||
headers=admin_hdr,
|
||||
)
|
||||
assert r_regen_admin.status_code == 200, r_regen_admin.text
|
||||
regen_body = r_regen_admin.json()
|
||||
assert regen_body["section"] == "comparison"
|
||||
assert regen_body["narrative"]["source"] == "rule_based"
|
||||
assert regen_body["narrative"]["headline"]
|
||||
|
||||
|
||||
def test_ai6_scoping_department_category_and_custom_period(client, db):
|
||||
mgmt_hdr = _auth_headers(client, "mgmt@poona.demo")
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
cat = db.query(Category).first()
|
||||
assert icu is not None and cat is not None
|
||||
|
||||
r_dept = client.get(f"/api/ai/depreciation?period=6m&department_id={icu.id}", headers=mgmt_hdr)
|
||||
assert r_dept.status_code == 200, r_dept.text
|
||||
dep_body = r_dept.json()
|
||||
assert len(dep_body["rows"]) > 0
|
||||
assert all(row["department_name"] == icu.name for row in dep_body["rows"])
|
||||
|
||||
r_cat = client.get(f"/api/ai/breakdown-frequency?period=3m&category_id={cat.id}", headers=mgmt_hdr)
|
||||
assert r_cat.status_code == 200, r_cat.text
|
||||
bf_body = r_cat.json()
|
||||
assert all(row["category_name"] == cat.name for row in bf_body["rows"])
|
||||
|
||||
# Valid custom period
|
||||
r_custom = client.get(
|
||||
"/api/ai/efficiency?period=custom&date_from=2025-01-01&date_to=2025-12-31",
|
||||
headers=mgmt_hdr,
|
||||
)
|
||||
assert r_custom.status_code == 200, r_custom.text
|
||||
assert r_custom.json()["period_start"] == "2025-01-01"
|
||||
assert r_custom.json()["period_end"] == "2025-12-31"
|
||||
|
||||
# Inverted custom period -> 422
|
||||
r_bad = client.get(
|
||||
"/api/ai/efficiency?period=custom&date_from=2026-06-01&date_to=2026-01-01",
|
||||
headers=mgmt_hdr,
|
||||
)
|
||||
assert r_bad.status_code == 422
|
||||
|
||||
|
||||
def test_ai6_default_none_provider_shapes_and_real_seeded_data(client, monkeypatch):
|
||||
from app.core.config import settings
|
||||
monkeypatch.setattr(settings, "AI_PROVIDER", "none")
|
||||
admin_hdr = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
status_res = client.get("/api/ai/status", headers=admin_hdr)
|
||||
assert status_res.status_code == 200
|
||||
st = status_res.json()
|
||||
assert st["provider"] == "none"
|
||||
assert st["enabled"] is False
|
||||
assert st["reachable"] is False
|
||||
|
||||
summary = client.get("/api/ai/summary?period=12m", headers=admin_hdr).json()
|
||||
assert set(summary["sections"].keys()) == {
|
||||
"comparison",
|
||||
"depreciation",
|
||||
"efficiency",
|
||||
"breakdown_frequency",
|
||||
}
|
||||
assert summary["narrative"]["source"] == "rule_based"
|
||||
assert len(summary["suggestions"]) > 0
|
||||
|
||||
for ep in ("comparison", "depreciation", "efficiency", "breakdown-frequency"):
|
||||
body = client.get(f"/api/ai/{ep}?period=12m", headers=admin_hdr).json()
|
||||
for key in ("metrics", "rows", "chart_data", "narrative", "how_calculated"):
|
||||
assert key in body, f"Missing '{key}' in /api/ai/{ep}"
|
||||
assert body["narrative"]["source"] == "rule_based"
|
||||
assert len(body["metrics"]) > 0
|
||||
assert len(body["rows"]) > 0
|
||||
|
||||
cmp_body = client.get("/api/ai/comparison?period=12m", headers=admin_hdr).json()
|
||||
assert len(cmp_body["rows"]) == 10
|
||||
|
||||
sugs = client.get("/api/ai/suggestions?period=12m", headers=admin_hdr).json()["suggestions"]
|
||||
s1 = [s for s in sugs if s["rule"] == "S1"]
|
||||
s4 = [s for s in sugs if s["rule"] == "S4"]
|
||||
assert len(s1) >= 3
|
||||
assert len(s4) >= 2
|
||||
|
||||
|
||||
def test_ai6_exports_xlsx_three_sheets_and_csv(client):
|
||||
biomed_hdr = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
for sec in AI_EXPORT_SECTIONS:
|
||||
r_xlsx = client.get(f"/api/ai/{sec}/export?format=xlsx&period=12m", headers=biomed_hdr)
|
||||
assert r_xlsx.status_code == 200, f"XLSX export failed for {sec}: {r_xlsx.text}"
|
||||
assert "spreadsheetml" in r_xlsx.headers["content-type"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(r_xlsx.content))
|
||||
assert len(wb.sheetnames) == 3, f"Expected 3 sheets for {sec}, got {wb.sheetnames}"
|
||||
assert wb.sheetnames[1] == "Evidence"
|
||||
assert wb.sheetnames[2] == "How calculated"
|
||||
assert len(wb.sheetnames[0]) <= 31
|
||||
|
||||
# Verify each sheet has header row (row 5) and at least one data row (row 6)
|
||||
for ws_name in wb.sheetnames:
|
||||
ws = wb[ws_name]
|
||||
assert ws.cell(row=5, column=1).value is not None, f"Missing header on {sec}/{ws_name}"
|
||||
assert ws.cell(row=6, column=1).value is not None, f"Missing data row on {sec}/{ws_name}"
|
||||
|
||||
r_csv = client.get(f"/api/ai/{sec}/export?format=csv&period=12m", headers=biomed_hdr)
|
||||
assert r_csv.status_code == 200, f"CSV export failed for {sec}: {r_csv.text}"
|
||||
assert "text/csv" in r_csv.headers["content-type"]
|
||||
assert len(r_csv.text.splitlines()) >= 5
|
||||
|
||||
# Unknown export section -> 404
|
||||
r_404 = client.get("/api/ai/nonexistent/export?format=xlsx", headers=biomed_hdr)
|
||||
assert r_404.status_code == 404
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
from io import BytesIO
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.models import Asset, AuditLog
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_bulk_import_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("bulk_import_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 _make_xlsx_bytes(headers: list[str], rows: list[list[object]]) -> bytes:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Assets"
|
||||
ws.append(headers)
|
||||
for r in rows:
|
||||
ws.append(r)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_import_template_download_and_rbac(client):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
for email in ("dept@poona.demo", "coord@poona.demo", "mgmt@poona.demo"):
|
||||
h = _auth_headers(client, email)
|
||||
assert client.get("/api/assets/import-template", headers=h).status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/assets/bulk-import",
|
||||
headers=h,
|
||||
files={"file": ("assets.csv", b"asset_code\n", "text/csv")},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
res = client.get("/api/assets/import-template", headers=bio_headers)
|
||||
assert res.status_code == 200
|
||||
assert "spreadsheetml.sheet" in res.headers["content-type"]
|
||||
assert 'filename="asset_import_template.xlsx"' in res.headers["content-disposition"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(res.content))
|
||||
assert wb.sheetnames == ["Assets", "Example", "Master Reference"]
|
||||
assert wb["Example"].cell(row=1, column=1).value == "Example only - this sheet is ignored on import"
|
||||
ws = wb["Assets"]
|
||||
headers = [ws.cell(row=1, column=i).value for i in range(1, 16)]
|
||||
assert headers[:6] == ["asset_code", "serial_no", "name", "category", "department", "location"]
|
||||
assert ws.freeze_panes == "A2"
|
||||
|
||||
# Admin also allowed
|
||||
assert client.get("/api/assets/import-template", headers=admin_headers).status_code == 200
|
||||
|
||||
|
||||
def test_bulk_import_dry_run_validation_and_commit(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
# Read a valid sample from template so we match real seeded department/location/category
|
||||
tmpl_res = client.get("/api/assets/import-template", headers=bio_headers)
|
||||
wb_tmpl = openpyxl.load_workbook(BytesIO(tmpl_res.content))
|
||||
ws_tmpl = wb_tmpl["Example"]
|
||||
headers = [wb_tmpl["Assets"].cell(row=1, column=i).value for i in range(1, 16)]
|
||||
cat_name = ws_tmpl.cell(row=2, column=4).value
|
||||
dept_code = ws_tmpl.cell(row=2, column=5).value
|
||||
loc_name = ws_tmpl.cell(row=2, column=6).value
|
||||
sup_name = ws_tmpl.cell(row=2, column=7).value
|
||||
|
||||
initial_count = db.query(Asset).count()
|
||||
|
||||
# Mix: 2 valid rows + 1 invalid row (unknown department)
|
||||
rows = [
|
||||
[
|
||||
"BLK-IMP-001",
|
||||
"BLK-SN-001",
|
||||
"Bulk Infusion Pump",
|
||||
cat_name,
|
||||
dept_code,
|
||||
loc_name,
|
||||
sup_name,
|
||||
95000,
|
||||
"2025-02-01",
|
||||
"2025-02-05",
|
||||
"in_service",
|
||||
"critical",
|
||||
"yes",
|
||||
"no",
|
||||
"Dry run test row 1",
|
||||
],
|
||||
[
|
||||
"BLK-IMP-002",
|
||||
"BLK-SN-002",
|
||||
"Bulk Syringe Pump",
|
||||
cat_name,
|
||||
dept_code,
|
||||
loc_name,
|
||||
"",
|
||||
45000,
|
||||
"15-Feb-2025",
|
||||
"",
|
||||
"in_service",
|
||||
"non_critical",
|
||||
"false",
|
||||
"true",
|
||||
"Dry run test row 2",
|
||||
],
|
||||
[
|
||||
"BLK-IMP-BAD",
|
||||
"BLK-SN-BAD",
|
||||
"Invalid Dept Equipment",
|
||||
cat_name,
|
||||
"NO_SUCH_DEPT",
|
||||
loc_name,
|
||||
"",
|
||||
10000,
|
||||
"",
|
||||
"",
|
||||
"in_service",
|
||||
"non_critical",
|
||||
"false",
|
||||
"false",
|
||||
"",
|
||||
],
|
||||
]
|
||||
xlsx_bytes = _make_xlsx_bytes(headers, rows)
|
||||
|
||||
# 1. dry_run=true validates all 3 without inserting into DB
|
||||
dry_res = client.post(
|
||||
"/api/assets/bulk-import?dry_run=true",
|
||||
headers=bio_headers,
|
||||
files={
|
||||
"file": (
|
||||
"bulk_assets.xlsx",
|
||||
xlsx_bytes,
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
},
|
||||
)
|
||||
assert dry_res.status_code == 200, dry_res.text
|
||||
dry_data = dry_res.json()
|
||||
assert dry_data["dry_run"] is True
|
||||
assert dry_data["total_rows"] == 3
|
||||
assert dry_data["valid_count"] == 2
|
||||
assert dry_data["error_count"] == 1
|
||||
assert dry_data["created_count"] == 0
|
||||
assert dry_data["errors"][0]["row"] == 4
|
||||
assert db.query(Asset).count() == initial_count
|
||||
|
||||
# 2. dry_run=false & skip_invalid=false rejects with 400 IMPORT_VALIDATION_ERRORS
|
||||
strict_res = client.post(
|
||||
"/api/assets/bulk-import?dry_run=false&skip_invalid=false",
|
||||
headers=bio_headers,
|
||||
files={
|
||||
"file": (
|
||||
"bulk_assets.xlsx",
|
||||
xlsx_bytes,
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
},
|
||||
)
|
||||
assert strict_res.status_code == 400
|
||||
assert strict_res.json()["code"] == "IMPORT_VALIDATION_ERRORS"
|
||||
assert db.query(Asset).count() == initial_count
|
||||
|
||||
# 3. dry_run=false & skip_invalid=true imports the 2 valid rows and logs audit entries
|
||||
skip_res = client.post(
|
||||
"/api/assets/bulk-import?dry_run=false&skip_invalid=true",
|
||||
headers=bio_headers,
|
||||
files={
|
||||
"file": (
|
||||
"bulk_assets.xlsx",
|
||||
xlsx_bytes,
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
},
|
||||
)
|
||||
assert skip_res.status_code == 200, skip_res.text
|
||||
skip_data = skip_res.json()
|
||||
assert skip_data["created_count"] == 2
|
||||
assert skip_data["error_count"] == 1
|
||||
assert db.query(Asset).count() == initial_count + 2
|
||||
|
||||
created_asset = db.query(Asset).filter(Asset.asset_code == "BLK-IMP-001").first()
|
||||
assert created_asset is not None
|
||||
audit = (
|
||||
db.query(AuditLog)
|
||||
.filter(
|
||||
AuditLog.entity_type == "asset",
|
||||
AuditLog.entity_id == created_asset.id,
|
||||
AuditLog.action == "bulk_import",
|
||||
)
|
||||
.first()
|
||||
)
|
||||
assert audit is not None
|
||||
|
||||
# 4. CSV import (all valid) + unsupported extension rejected
|
||||
csv_bytes = (
|
||||
"asset_code,serial_no,name,category,department,location\n"
|
||||
f"BLK-CSV-003,SN-CSV-003,CSV Patient Monitor,{cat_name},{dept_code},{loc_name}\n"
|
||||
).encode("utf-8")
|
||||
csv_res = client.post(
|
||||
"/api/assets/bulk-import?dry_run=false",
|
||||
headers=bio_headers,
|
||||
files={"file": ("assets.csv", csv_bytes, "text/csv")},
|
||||
)
|
||||
assert csv_res.status_code == 200, csv_res.text
|
||||
assert csv_res.json()["created_count"] == 1
|
||||
|
||||
bad_ext = client.post(
|
||||
"/api/assets/bulk-import",
|
||||
headers=bio_headers,
|
||||
files={"file": ("assets.txt", b"hello", "text/plain")},
|
||||
)
|
||||
assert bad_ext.status_code == 400
|
||||
assert bad_ext.json()["code"] == "INVALID_FILE_TYPE"
|
||||
@@ -0,0 +1,336 @@
|
||||
from datetime import date, timedelta
|
||||
import io
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
import pytest
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models import Asset, AuditLog, Category, Complaint, Department, Location
|
||||
from app.seed.seed import _make_minimal_pdf, seed_database
|
||||
from app.services.calculations import alert_state, compute_schedule_status, coverage_status
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_assets_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("asset_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 _make_png_bytes() -> bytes:
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (32, 32), color=(10, 120, 200)).save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _make_jpeg_bytes() -> bytes:
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (32, 32), color=(200, 50, 50)).save(buf, format="JPEG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_alert_state_and_coverage_status():
|
||||
today = date(2026, 5, 1)
|
||||
|
||||
assert alert_state(None, today, lead_days=30, red_days=7) == "ok"
|
||||
assert alert_state(today - timedelta(days=1), today, 30, 7) == "red"
|
||||
assert alert_state(today, today, 30, 7) == "red"
|
||||
assert alert_state(today + timedelta(days=7), today, 30, 7) == "red"
|
||||
assert alert_state(today + timedelta(days=8), today, 30, 7) == "yellow"
|
||||
assert alert_state(today + timedelta(days=30), today, 30, 7) == "yellow"
|
||||
assert alert_state(today + timedelta(days=31), today, 30, 7) == "ok"
|
||||
|
||||
assert coverage_status(None, None, today, 30, 7) == ("none", "none")
|
||||
assert coverage_status(today - timedelta(days=100), today - timedelta(days=1), today, 30, 7) == ("expired", "red")
|
||||
assert coverage_status(today - timedelta(days=100), today + timedelta(days=5), today, 30, 7) == ("expiring", "red")
|
||||
assert coverage_status(today - timedelta(days=100), today + timedelta(days=20), today, 30, 7) == ("expiring", "yellow")
|
||||
assert coverage_status(today - timedelta(days=100), today + timedelta(days=45), today, 30, 7) == ("active", "ok")
|
||||
|
||||
assert compute_schedule_status(today - timedelta(days=1), "completed", today, 15, 7) == ("completed", "ok")
|
||||
assert compute_schedule_status(today - timedelta(days=1), None, today, 15, 7) == ("overdue", "red")
|
||||
assert compute_schedule_status(today + timedelta(days=10), None, today, 15, 7) == ("due", "yellow")
|
||||
assert compute_schedule_status(today + timedelta(days=30), None, today, 15, 7) == ("upcoming", "ok")
|
||||
|
||||
|
||||
def test_asset_crud_and_duplicate_code(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
loc = db.query(Location).filter(Location.department_id == icu.id).first()
|
||||
cat = db.query(Category).first()
|
||||
|
||||
# department_user cannot create assets
|
||||
forbidden_create = client.post(
|
||||
"/api/assets",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_code": "PHRC-ICU-9998",
|
||||
"serial_no": "SN-9998",
|
||||
"name": "Unauthorized Asset",
|
||||
"category_id": cat.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": loc.id,
|
||||
},
|
||||
)
|
||||
assert forbidden_create.status_code == 403
|
||||
|
||||
# biomedical creates asset
|
||||
create_res = client.post(
|
||||
"/api/assets",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_code": "PHRC-ICU-9999",
|
||||
"serial_no": "SN-TEST-9999",
|
||||
"name": "Test Cardiac Monitor",
|
||||
"category_id": cat.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": loc.id,
|
||||
"purchase_value": 250000.0,
|
||||
"status": "in_service",
|
||||
"criticality": "critical",
|
||||
"requires_calibration": True,
|
||||
"insurance_applicable": True,
|
||||
"remarks": "Phase 2 test asset",
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
created = create_res.json()
|
||||
assert created["asset_code"] == "PHRC-ICU-9999"
|
||||
assert created["department_name"] == icu.name
|
||||
|
||||
# Duplicate asset_code -> 409 DUPLICATE_ASSET_CODE
|
||||
dup_res = client.post(
|
||||
"/api/assets",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_code": "PHRC-ICU-9999",
|
||||
"serial_no": "SN-DUP",
|
||||
"name": "Duplicate Asset",
|
||||
"category_id": cat.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": loc.id,
|
||||
},
|
||||
)
|
||||
assert dup_res.status_code == 409
|
||||
assert dup_res.json()["code"] == "DUPLICATE_ASSET_CODE"
|
||||
|
||||
# Audit log written on create
|
||||
audit = (
|
||||
db.query(AuditLog)
|
||||
.filter(AuditLog.entity_type == "asset", AuditLog.entity_id == created["id"], AuditLog.action == "create")
|
||||
.first()
|
||||
)
|
||||
assert audit is not None
|
||||
|
||||
# Overview returns structured data
|
||||
ov_res = client.get(f"/api/assets/{created['id']}/overview", headers=bio_headers)
|
||||
assert ov_res.status_code == 200
|
||||
ov = ov_res.json()
|
||||
assert ov["asset"]["id"] == created["id"]
|
||||
assert "warranties" in ov
|
||||
assert "contracts" in ov
|
||||
assert "attachments" in ov
|
||||
|
||||
|
||||
def test_department_user_scoping_on_assets(client, db):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
ot = db.query(Department).filter(Department.code == "OT").first()
|
||||
other_asset = db.query(Asset).filter(Asset.department_id == ot.id).first()
|
||||
assert other_asset is not None
|
||||
|
||||
# List returns only ICU assets even if another department_id is requested
|
||||
list_res = client.get(f"/api/assets?department_id={ot.id}&page_size=200", headers=dept_headers)
|
||||
assert list_res.status_code == 200
|
||||
items = list_res.json()["items"]
|
||||
assert len(items) > 0
|
||||
assert all(item["department_id"] == icu.id for item in items)
|
||||
|
||||
# Lookup returns only ICU assets
|
||||
lookup_res = client.get(f"/api/assets/lookup?department_id={ot.id}", headers=dept_headers)
|
||||
assert lookup_res.status_code == 200
|
||||
lookup_items = lookup_res.json()["items"]
|
||||
assert all(item["department_id"] == icu.id for item in lookup_items)
|
||||
|
||||
# Direct access to another department's asset & overview -> 403
|
||||
assert client.get(f"/api/assets/{other_asset.id}", headers=dept_headers).status_code == 403
|
||||
assert client.get(f"/api/assets/{other_asset.id}/overview", headers=dept_headers).status_code == 403
|
||||
|
||||
|
||||
def test_coordinator_field_level_patch_restrictions(client, db):
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
asset = db.query(Asset).first()
|
||||
|
||||
ok_patch = client.patch(
|
||||
f"/api/assets/{asset.id}",
|
||||
headers=coord_headers,
|
||||
json={"insurance_applicable": not asset.insurance_applicable, "remarks": "Updated by coordinator"},
|
||||
)
|
||||
assert ok_patch.status_code == 200
|
||||
assert ok_patch.json()["remarks"] == "Updated by coordinator"
|
||||
|
||||
bad_name = client.patch(
|
||||
f"/api/assets/{asset.id}",
|
||||
headers=coord_headers,
|
||||
json={"name": "Unauthorized Rename"},
|
||||
)
|
||||
assert bad_name.status_code == 403
|
||||
assert bad_name.json()["code"] == "FORBIDDEN"
|
||||
|
||||
bad_status = client.patch(
|
||||
f"/api/assets/{asset.id}",
|
||||
headers=coord_headers,
|
||||
json={"status": "condemned"},
|
||||
)
|
||||
assert bad_status.status_code == 403
|
||||
assert bad_status.json()["code"] == "FORBIDDEN"
|
||||
|
||||
|
||||
def test_attachments_upload_download_delete_and_security(client, db, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(settings, "UPLOAD_DIR", str(tmp_path))
|
||||
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
ot = db.query(Department).filter(Department.code == "OT").first()
|
||||
icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first()
|
||||
ot_asset = db.query(Asset).filter(Asset.department_id == ot.id).first()
|
||||
icu_complaint = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.filter(Asset.department_id == icu.id)
|
||||
.first()
|
||||
)
|
||||
assert icu_complaint is not None
|
||||
|
||||
# 1. Valid PNG upload & download exact bytes
|
||||
png_bytes = _make_png_bytes()
|
||||
up_png = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("panel.png", png_bytes, "image/png")},
|
||||
)
|
||||
assert up_png.status_code == 201, up_png.text
|
||||
att_id = up_png.json()["id"]
|
||||
assert up_png.json()["mime_type"] == "image/png"
|
||||
|
||||
dl_res = client.get(f"/api/attachments/{att_id}/download", headers=bio_headers)
|
||||
assert dl_res.status_code == 200
|
||||
assert dl_res.content == png_bytes
|
||||
|
||||
# 2. Valid JPG and PDF uploads
|
||||
jpg_bytes = _make_jpeg_bytes()
|
||||
up_jpg = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("photo.jpg", jpg_bytes, "image/jpeg")},
|
||||
)
|
||||
assert up_jpg.status_code == 201
|
||||
|
||||
pdf_bytes = _make_minimal_pdf("Asset Service Manual")
|
||||
up_pdf = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("manual.pdf", pdf_bytes, "application/pdf")},
|
||||
)
|
||||
assert up_pdf.status_code == 201
|
||||
|
||||
# 3. Reject .exe / .txt and spoofed magic bytes -> 400 INVALID_FILE_TYPE
|
||||
bad_exe = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("malware.exe", b"MZ\x90\x00", "application/octet-stream")},
|
||||
)
|
||||
assert bad_exe.status_code == 400
|
||||
assert bad_exe.json()["code"] == "INVALID_FILE_TYPE"
|
||||
|
||||
bad_spoof = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("fake.jpg", b"not really a jpeg", "image/jpeg")},
|
||||
)
|
||||
assert bad_spoof.status_code == 400
|
||||
assert bad_spoof.json()["code"] == "INVALID_FILE_TYPE"
|
||||
|
||||
# 4. Reject >10 MB -> 413 FILE_TOO_LARGE
|
||||
oversized = b"%PDF-" + (b"0" * (10 * 1024 * 1024 + 100))
|
||||
too_big = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("huge.pdf", oversized, "application/pdf")},
|
||||
)
|
||||
assert too_big.status_code == 413
|
||||
assert too_big.json()["code"] == "FILE_TOO_LARGE"
|
||||
|
||||
# 5. department_user cannot upload to or download from another department's asset
|
||||
ot_up = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(ot_asset.id)},
|
||||
files={"file": ("ot.png", png_bytes, "image/png")},
|
||||
)
|
||||
assert ot_up.status_code == 201
|
||||
ot_att_id = ot_up.json()["id"]
|
||||
|
||||
assert client.get(f"/api/attachments/{ot_att_id}/download", headers=dept_headers).status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/attachments",
|
||||
headers=dept_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(ot_asset.id)},
|
||||
files={"file": ("unauth.png", png_bytes, "image/png")},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# department_user cannot upload to own-dept asset (only complaint), CAN upload to own-dept complaint
|
||||
assert (
|
||||
client.post(
|
||||
"/api/attachments",
|
||||
headers=dept_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("icu.png", png_bytes, "image/png")},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
dept_cmp_up = client.post(
|
||||
"/api/attachments",
|
||||
headers=dept_headers,
|
||||
data={"entity_type": "complaint", "entity_id": str(icu_complaint.id)},
|
||||
files={"file": ("fault.jpg", jpg_bytes, "image/jpeg")},
|
||||
)
|
||||
assert dept_cmp_up.status_code == 201
|
||||
|
||||
# management cannot upload or delete
|
||||
assert (
|
||||
client.post(
|
||||
"/api/attachments",
|
||||
headers=mgmt_headers,
|
||||
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||
files={"file": ("mgmt.png", png_bytes, "image/png")},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert client.delete(f"/api/attachments/{att_id}", headers=mgmt_headers).status_code == 403
|
||||
|
||||
# Delete removes DB row and disk file
|
||||
stored_files_before = list(Path(tmp_path).iterdir())
|
||||
del_res = client.delete(f"/api/attachments/{att_id}", headers=bio_headers)
|
||||
assert del_res.status_code == 204
|
||||
stored_files_after = list(Path(tmp_path).iterdir())
|
||||
assert len(stored_files_after) == len(stored_files_before) - 1
|
||||
assert client.get(f"/api/attachments/{att_id}/download", headers=bio_headers).status_code == 404
|
||||
@@ -0,0 +1,390 @@
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import KOLKATA, effective_today
|
||||
from app.models import (
|
||||
Asset,
|
||||
Attachment,
|
||||
CalibrationPlan,
|
||||
Category,
|
||||
Complaint,
|
||||
Contract,
|
||||
DemoEquipment,
|
||||
Department,
|
||||
DepartmentVisit,
|
||||
InsurancePolicy,
|
||||
Location,
|
||||
PMSchedule,
|
||||
User,
|
||||
Vendor,
|
||||
Warranty,
|
||||
)
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.permissions import RESTRICTED_COMPLAINT_FIELDS, Role, has_capability
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_test_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str, password: str = "Demo@123") -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": password})
|
||||
assert res.status_code == 200, res.text
|
||||
token = res.json()["access_token"]
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def test_login_valid_and_invalid(client, db):
|
||||
res = client.post("/api/auth/login", json={"email": "admin@poona.demo", "password": "Demo@123"})
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["token_type"] == "bearer"
|
||||
assert body["access_token"]
|
||||
assert body["user"]["email"] == "admin@poona.demo"
|
||||
assert body["user"]["role"] == "system_admin"
|
||||
assert body["user"]["demo_as_of_date"] is None
|
||||
|
||||
bad_pw = client.post("/api/auth/login", json={"email": "admin@poona.demo", "password": "wrong"})
|
||||
assert bad_pw.status_code == 401
|
||||
|
||||
bad_email = client.post("/api/auth/login", json={"email": "nobody@poona.demo", "password": "Demo@123"})
|
||||
assert bad_email.status_code == 401
|
||||
|
||||
# Inactive user rejected
|
||||
user = db.query(User).filter(User.email == "neha.chavan@poona.demo").first()
|
||||
assert user is not None
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
try:
|
||||
res_inactive = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "neha.chavan@poona.demo", "password": "Demo@123"},
|
||||
)
|
||||
assert res_inactive.status_code in (401, 403)
|
||||
finally:
|
||||
user.is_active = True
|
||||
db.commit()
|
||||
|
||||
|
||||
def test_auth_me(client):
|
||||
unauth = client.get("/api/auth/me")
|
||||
assert unauth.status_code == 401
|
||||
|
||||
bad_tok = client.get("/api/auth/me", headers={"Authorization": "Bearer invalid.token.here"})
|
||||
assert bad_tok.status_code == 401
|
||||
|
||||
headers = _auth_headers(client, "dept@poona.demo")
|
||||
me = client.get("/api/auth/me", headers=headers)
|
||||
assert me.status_code == 200
|
||||
data = me.json()
|
||||
assert data["email"] == "dept@poona.demo"
|
||||
assert data["role"] == "department_user"
|
||||
assert data["department_name"] == "Intensive Care Unit"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"email",
|
||||
[
|
||||
"bio@poona.demo",
|
||||
"dept@poona.demo",
|
||||
"mgmt@poona.demo",
|
||||
"coord@poona.demo",
|
||||
],
|
||||
)
|
||||
def test_non_admin_forbidden_on_admin_endpoints(client, db, email):
|
||||
headers = _auth_headers(client, email)
|
||||
dept = db.query(Department).first()
|
||||
target_user = db.query(User).filter(User.email == "dept@poona.demo").first()
|
||||
|
||||
# Masters GET is allowed for authenticated users
|
||||
assert client.get("/api/departments", headers=headers).status_code == 200
|
||||
assert client.get("/api/locations", headers=headers).status_code == 200
|
||||
assert client.get("/api/categories", headers=headers).status_code == 200
|
||||
assert client.get("/api/vendors", headers=headers).status_code == 200
|
||||
assert client.get("/api/users/lookup", headers=headers).status_code == 200
|
||||
|
||||
# Masters write -> 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/departments",
|
||||
headers=headers,
|
||||
json={"name": "Test Dept", "code": "TST"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/departments/{dept.id}",
|
||||
headers=headers,
|
||||
json={"description": "hacked"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert client.delete(f"/api/departments/{dept.id}", headers=headers).status_code == 403
|
||||
|
||||
# Users admin endpoints -> 403
|
||||
assert client.get("/api/users", headers=headers).status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Hack",
|
||||
"email": "hack@poona.demo",
|
||||
"password": "Password1",
|
||||
"role": "biomedical",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/users/{target_user.id}",
|
||||
headers=headers,
|
||||
json={"name": "Hacked"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert client.delete(f"/api/users/{target_user.id}", headers=headers).status_code == 403
|
||||
|
||||
# Settings endpoints -> 403
|
||||
assert client.get("/api/settings", headers=headers).status_code == 403
|
||||
assert (
|
||||
client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"contract_expiry_alert_days": 45}},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=headers,
|
||||
json={"demo_as_of_date": "2026-06-01"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
|
||||
def test_admin_masters_and_users_crud(client):
|
||||
headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
# Department create, patch, soft-delete
|
||||
r = client.post(
|
||||
"/api/departments",
|
||||
headers=headers,
|
||||
json={"name": "Physiotherapy", "code": "PHYS", "description": "Rehab unit"},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
dept_id = r.json()["id"]
|
||||
|
||||
r_patch = client.patch(
|
||||
f"/api/departments/{dept_id}",
|
||||
headers=headers,
|
||||
json={"description": "Physiotherapy & Rehab"},
|
||||
)
|
||||
assert r_patch.status_code == 200
|
||||
assert r_patch.json()["description"] == "Physiotherapy & Rehab"
|
||||
|
||||
r_del = client.delete(f"/api/departments/{dept_id}", headers=headers)
|
||||
assert r_del.status_code == 200
|
||||
assert r_del.json()["is_active"] is False
|
||||
|
||||
# User create, password update, soft-delete
|
||||
u_res = client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Temp Staff",
|
||||
"email": "temp.staff@poona.demo",
|
||||
"password": "InitPassword1",
|
||||
"role": "biomedical",
|
||||
},
|
||||
)
|
||||
assert u_res.status_code == 201
|
||||
uid = u_res.json()["id"]
|
||||
|
||||
# Update password
|
||||
u_patch = client.patch(
|
||||
f"/api/users/{uid}",
|
||||
headers=headers,
|
||||
json={"password": "NewPassword2"},
|
||||
)
|
||||
assert u_patch.status_code == 200
|
||||
login_new = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "temp.staff@poona.demo", "password": "NewPassword2"},
|
||||
)
|
||||
assert login_new.status_code == 200
|
||||
|
||||
# Soft delete user
|
||||
u_del = client.delete(f"/api/users/{uid}", headers=headers)
|
||||
assert u_del.status_code == 200
|
||||
assert u_del.json()["is_active"] is False
|
||||
|
||||
|
||||
def test_permissions_matrix_all_roles():
|
||||
assert "action_taken" in RESTRICTED_COMPLAINT_FIELDS
|
||||
assert "spare_cost_estimate" in RESTRICTED_COMPLAINT_FIELDS
|
||||
|
||||
# system_admin
|
||||
assert has_capability(Role.system_admin, "manage_admin") is True
|
||||
assert has_capability(Role.system_admin, "edit_technical_fields") is True
|
||||
assert has_capability(Role.system_admin, "view_visits") is True
|
||||
|
||||
# biomedical
|
||||
assert has_capability(Role.biomedical, "manage_admin") is False
|
||||
assert has_capability(Role.biomedical, "create_edit_assets") is True
|
||||
assert has_capability(Role.biomedical, "edit_technical_fields") is True
|
||||
assert has_capability(Role.biomedical, "manage_pm") is True
|
||||
assert has_capability(Role.biomedical, "manage_visits") is True
|
||||
assert has_capability(Role.biomedical, "view_all_reports") is True
|
||||
|
||||
# department_user
|
||||
assert has_capability(Role.department_user, "manage_admin") is False
|
||||
assert has_capability(Role.department_user, "view_assets") is True
|
||||
assert has_capability(Role.department_user, "raise_complaint") is True
|
||||
assert has_capability(Role.department_user, "handle_complaint") is False
|
||||
assert has_capability(Role.department_user, "edit_technical_fields") is False
|
||||
assert has_capability(Role.department_user, "view_visits") is False
|
||||
assert has_capability(Role.department_user, "view_dept_reports") is True
|
||||
assert has_capability(Role.department_user, "view_all_reports") is False
|
||||
|
||||
# management
|
||||
assert has_capability(Role.management, "manage_admin") is False
|
||||
assert has_capability(Role.management, "view_assets") is True
|
||||
assert has_capability(Role.management, "view_visits") is True
|
||||
assert has_capability(Role.management, "view_all_reports") is True
|
||||
assert has_capability(Role.management, "create_edit_assets") is False
|
||||
assert has_capability(Role.management, "raise_complaint") is False
|
||||
assert has_capability(Role.management, "edit_technical_fields") is False
|
||||
|
||||
# coordinator
|
||||
assert has_capability(Role.coordinator, "manage_admin") is False
|
||||
assert has_capability(Role.coordinator, "raise_complaint") is False
|
||||
assert has_capability(Role.coordinator, "edit_asset_contracts_only") is True
|
||||
assert has_capability(Role.coordinator, "handle_complaint") is True
|
||||
assert has_capability(Role.coordinator, "edit_technical_fields") is False
|
||||
assert has_capability(Role.coordinator, "manage_calibration_contracts") is True
|
||||
assert has_capability(Role.coordinator, "manage_demo_equipment") is True
|
||||
assert has_capability(Role.coordinator, "view_visits") is False
|
||||
|
||||
# invalid / None
|
||||
assert has_capability(None, "view_assets") is False
|
||||
assert has_capability("unknown_role", "view_assets") is False
|
||||
|
||||
|
||||
def test_settings_validation_and_demo_date(client, db):
|
||||
headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
res = client.get("/api/settings", headers=headers)
|
||||
assert res.status_code == 200
|
||||
items = res.json()["items"]
|
||||
assert len(items) >= 14
|
||||
|
||||
# Out of range int
|
||||
bad_range = client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"contract_expiry_alert_days": 999}},
|
||||
)
|
||||
assert bad_range.status_code == 422
|
||||
|
||||
# Bool passed to int
|
||||
bad_type = client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"contract_expiry_alert_days": True}},
|
||||
)
|
||||
assert bad_type.status_code == 422
|
||||
|
||||
# Invalid enum
|
||||
bad_enum = client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"default_pm_mode": "third_party"}},
|
||||
)
|
||||
assert bad_enum.status_code == 422
|
||||
|
||||
# Unknown key
|
||||
bad_key = client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"nonexistent_key": 123}},
|
||||
)
|
||||
assert bad_key.status_code == 422
|
||||
|
||||
# Valid update
|
||||
ok_put = client.put(
|
||||
"/api/settings",
|
||||
headers=headers,
|
||||
json={"values": {"contract_expiry_alert_days": 45, "require_closure_remarks": False}},
|
||||
)
|
||||
assert ok_put.status_code == 200
|
||||
updated_map = {item["key"]: item["value"] for item in ok_put.json()["items"]}
|
||||
assert updated_map["contract_expiry_alert_days"] == 45
|
||||
assert updated_map["require_closure_remarks"] is False
|
||||
|
||||
# Demo date set & reset
|
||||
set_demo = client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=headers,
|
||||
json={"demo_as_of_date": "2026-06-15"},
|
||||
)
|
||||
assert set_demo.status_code == 200
|
||||
assert set_demo.json()["demo_as_of_date"] == "2026-06-15"
|
||||
assert set_demo.json()["effective_today"] == "2026-06-15"
|
||||
assert effective_today(db) == date(2026, 6, 15)
|
||||
|
||||
me_res = client.get("/api/auth/me", headers=headers)
|
||||
assert me_res.json()["demo_as_of_date"] == "2026-06-15"
|
||||
|
||||
# Reset demo date
|
||||
reset_demo = client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=headers,
|
||||
json={"demo_as_of_date": None},
|
||||
)
|
||||
assert reset_demo.status_code == 200
|
||||
assert reset_demo.json()["demo_as_of_date"] is None
|
||||
assert effective_today(db) == datetime.now(KOLKATA).date()
|
||||
|
||||
|
||||
def test_seed_idempotency_and_counts(db, tmp_path):
|
||||
summary1 = seed_database(db, upload_dir=tmp_path)
|
||||
summary2 = seed_database(db, upload_dir=tmp_path)
|
||||
assert summary1 == summary2
|
||||
|
||||
assert db.query(Department).count() == 8
|
||||
assert db.query(Location).count() == 20
|
||||
assert db.query(Category).count() == 8
|
||||
assert db.query(Vendor).count() == 12
|
||||
assert db.query(User).count() == 11
|
||||
assert db.query(Asset).count() == 60
|
||||
assert db.query(Contract).count() == 35
|
||||
assert db.query(Contract).filter(Contract.is_superseded.is_(True)).count() == 1
|
||||
assert db.query(Warranty).count() == 20
|
||||
assert db.query(InsurancePolicy).count() == 25
|
||||
assert db.query(CalibrationPlan).count() == 20
|
||||
assert db.query(PMSchedule).count() == 45
|
||||
assert db.query(PMSchedule).filter(PMSchedule.service_mode == "in_house").count() == 27
|
||||
assert db.query(PMSchedule).filter(PMSchedule.service_mode == "outsourced").count() == 18
|
||||
assert db.query(Complaint).count() == 30
|
||||
assert db.query(Complaint).filter(Complaint.call_status == "closed").count() == 22
|
||||
assert db.query(Complaint).filter(Complaint.call_status == "in_progress").count() == 4
|
||||
assert db.query(Complaint).filter(Complaint.call_status == "open").count() == 4
|
||||
assert db.query(Complaint).filter(Complaint.spare_required.is_(True)).count() == 6
|
||||
assert db.query(Complaint).filter(Complaint.ce_name.is_not(None)).count() == 5
|
||||
assert db.query(DemoEquipment).count() == 3
|
||||
assert db.query(DepartmentVisit).count() == 12
|
||||
assert db.query(Attachment).count() == 14
|
||||
|
||||
jpegs = list(Path(tmp_path).glob("*.jpg"))
|
||||
pdfs = list(Path(tmp_path).glob("*.pdf"))
|
||||
assert len(jpegs) == 8
|
||||
assert len(pdfs) == 6
|
||||
@@ -0,0 +1,76 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tarfile
|
||||
import pytest
|
||||
|
||||
from scripts.backup import create_backup, get_db_path
|
||||
|
||||
|
||||
def test_get_db_path_relative_dot_slash():
|
||||
backend_dir = Path("/mock/backend").resolve()
|
||||
p = get_db_path("sqlite:///./data/ams.db", backend_dir)
|
||||
assert p == (backend_dir / "data" / "ams.db").resolve()
|
||||
|
||||
|
||||
def test_get_db_path_relative_plain():
|
||||
backend_dir = Path("/mock/backend").resolve()
|
||||
p = get_db_path("sqlite:///data/ams.db", backend_dir)
|
||||
assert p == (backend_dir / "data" / "ams.db").resolve()
|
||||
|
||||
|
||||
def test_get_db_path_absolute_app():
|
||||
backend_dir = Path("/mock/backend").resolve()
|
||||
p = get_db_path("sqlite:////app/data/ams.db", backend_dir)
|
||||
assert p == Path("/app/data/ams.db")
|
||||
|
||||
|
||||
def test_get_db_path_absolute_tmp():
|
||||
backend_dir = Path("/mock/backend").resolve()
|
||||
p = get_db_path("sqlite:////tmp/x/custom.db", backend_dir)
|
||||
assert p == Path("/tmp/x/custom.db")
|
||||
|
||||
|
||||
def test_get_db_path_fallbacks():
|
||||
backend_dir = Path("/mock/backend").resolve()
|
||||
default_expected = backend_dir / "data" / "ams.db"
|
||||
assert get_db_path(None, backend_dir) == default_expected
|
||||
assert get_db_path("", backend_dir) == default_expected
|
||||
assert get_db_path("sqlite:///:memory:", backend_dir) == default_expected
|
||||
assert get_db_path("postgresql://localhost/ams", backend_dir) == default_expected
|
||||
|
||||
|
||||
def test_create_backup_real_temp_sqlite_file(tmp_path):
|
||||
# Create real SQLite file
|
||||
db_file = tmp_path / "source.db"
|
||||
conn = sqlite3.connect(str(db_file))
|
||||
cur = conn.cursor()
|
||||
cur.execute("CREATE TABLE test_table (id INTEGER PRIMARY KEY, note TEXT);")
|
||||
cur.execute("INSERT INTO test_table (note) VALUES ('backup test');")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
uploads_dir = tmp_path / "uploads"
|
||||
uploads_dir.mkdir()
|
||||
(uploads_dir / "sample.pdf").write_bytes(b"%PDF-1.4 sample content")
|
||||
|
||||
dest_dir = tmp_path / "backups"
|
||||
dest_dir.mkdir()
|
||||
|
||||
# Run backup producing a .tar.gz
|
||||
archive_path = create_backup(
|
||||
db_path=db_file,
|
||||
uploads_dir=uploads_dir,
|
||||
dest_dir=dest_dir,
|
||||
archive_format="tar.gz",
|
||||
)
|
||||
assert archive_path is not None
|
||||
assert archive_path.exists()
|
||||
assert str(archive_path).endswith(".tar.gz")
|
||||
|
||||
# Verify that the tar.gz is valid and contains db.sqlite3
|
||||
with tarfile.open(archive_path, "r:gz") as tf:
|
||||
names = tf.getnames()
|
||||
assert "db.sqlite3" in names
|
||||
assert "ams.db" in names
|
||||
assert any("uploads/sample.pdf" in n for n in names)
|
||||
@@ -0,0 +1,239 @@
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.models import Asset, CalibrationPlan, CalibrationRecord, Contract, InsurancePolicy, Vendor
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_extra_import_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("extra_import_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 _make_xlsx_bytes(sheet_name: str, headers: list[str], rows: list[list[object]]) -> bytes:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = sheet_name
|
||||
ws.append(headers)
|
||||
for r in rows:
|
||||
ws.append(r)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_contracts_bulk_import_lifecycle(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset is not None
|
||||
assert vendor is not None
|
||||
|
||||
headers = [
|
||||
"asset_code",
|
||||
"provider_name",
|
||||
"contract_type",
|
||||
"start_date",
|
||||
"end_date",
|
||||
"cost",
|
||||
"coverage_details",
|
||||
"remarks",
|
||||
]
|
||||
|
||||
# 1 valid, 1 invalid (invalid contract_type)
|
||||
rows = [
|
||||
[
|
||||
asset.asset_code,
|
||||
vendor.name,
|
||||
"CMC",
|
||||
"2026-01-01",
|
||||
"2026-12-31",
|
||||
85000,
|
||||
"All parts included",
|
||||
"Annual contract",
|
||||
],
|
||||
[
|
||||
asset.asset_code,
|
||||
vendor.name,
|
||||
"INVALID_TYPE",
|
||||
"2026-01-01",
|
||||
"2026-12-31",
|
||||
50000,
|
||||
"Test",
|
||||
"Test remarks",
|
||||
],
|
||||
]
|
||||
|
||||
xlsx_bytes = _make_xlsx_bytes("Contracts", headers, rows)
|
||||
|
||||
# Dry run
|
||||
res = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["dry_run"] is True
|
||||
assert data["total_rows"] == 2
|
||||
assert data["valid_count"] == 1
|
||||
assert data["error_count"] == 1
|
||||
assert data["created_count"] == 0
|
||||
|
||||
# Fail commit without skip_invalid
|
||||
res_fail = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false&skip_invalid=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_fail.status_code == 400
|
||||
|
||||
# Commit with skip_invalid
|
||||
res_commit = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_commit.status_code == 200
|
||||
commit_data = res_commit.json()
|
||||
assert commit_data["created_count"] == 1
|
||||
|
||||
created_contract = (
|
||||
db.query(Contract)
|
||||
.filter(Contract.asset_id == asset.id, Contract.contract_type == "CMC")
|
||||
.order_by(Contract.id.desc())
|
||||
.first()
|
||||
)
|
||||
assert created_contract is not None
|
||||
assert created_contract.provider_id == vendor.id
|
||||
|
||||
|
||||
def test_calibration_bulk_import_lifecycle(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
# Find asset without calibration plan
|
||||
existing_plan_ids = [p.asset_id for p in db.query(CalibrationPlan.asset_id).all()]
|
||||
asset = db.query(Asset).filter(Asset.id.notin_(existing_plan_ids)).first()
|
||||
assert asset is not None
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert vendor is not None
|
||||
|
||||
headers = [
|
||||
"asset_code",
|
||||
"frequency_months",
|
||||
"agency_name",
|
||||
"scope",
|
||||
"standards",
|
||||
"remarks",
|
||||
]
|
||||
|
||||
rows = [
|
||||
[
|
||||
asset.asset_code,
|
||||
12,
|
||||
vendor.name,
|
||||
"Accuracy verification",
|
||||
"ISO 17025",
|
||||
"Imported plan",
|
||||
],
|
||||
]
|
||||
|
||||
xlsx_bytes = _make_xlsx_bytes("Calibration Plans", headers, rows)
|
||||
|
||||
# Dry run
|
||||
res = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["valid_count"] == 1
|
||||
assert data["error_count"] == 0
|
||||
|
||||
# Commit
|
||||
res_commit = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_commit.status_code == 200
|
||||
assert res_commit.json()["created_count"] == 1
|
||||
|
||||
plan = db.query(CalibrationPlan).filter(CalibrationPlan.asset_id == asset.id).first()
|
||||
assert plan is not None
|
||||
assert plan.frequency_months == 12
|
||||
|
||||
record = db.query(CalibrationRecord).filter(CalibrationRecord.plan_id == plan.id).first()
|
||||
assert record is not None
|
||||
|
||||
|
||||
def test_insurance_bulk_import_lifecycle(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset is not None
|
||||
assert vendor is not None
|
||||
|
||||
headers = [
|
||||
"asset_code",
|
||||
"insurer_name",
|
||||
"policy_number",
|
||||
"start_date",
|
||||
"end_date",
|
||||
"insured_value",
|
||||
"premium",
|
||||
"remarks",
|
||||
]
|
||||
|
||||
rows = [
|
||||
[
|
||||
asset.asset_code,
|
||||
vendor.name,
|
||||
"POL-TEST-9999",
|
||||
"2026-04-01",
|
||||
"2027-03-31",
|
||||
1200000,
|
||||
15000,
|
||||
"Annual equipment insurance",
|
||||
],
|
||||
]
|
||||
|
||||
xlsx_bytes = _make_xlsx_bytes("Insurance Policies", headers, rows)
|
||||
|
||||
# Dry run
|
||||
res = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["valid_count"] == 1
|
||||
assert data["error_count"] == 0
|
||||
|
||||
# Commit
|
||||
res_commit = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_commit.status_code == 200
|
||||
assert res_commit.json()["created_count"] == 1
|
||||
|
||||
pol = db.query(InsurancePolicy).filter(InsurancePolicy.policy_no == "POL-TEST-9999").first()
|
||||
assert pol is not None
|
||||
assert pol.coverage_amount == 1200000
|
||||
assert pol.asset_id == asset.id
|
||||
|
||||
@@ -0,0 +1,602 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import KOLKATA
|
||||
from app.models import Asset, Complaint, Department, User
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.calculations import (
|
||||
clip_downtime_to_month,
|
||||
compute_ce_response_time_minutes,
|
||||
compute_downtime_minutes,
|
||||
compute_response_time_minutes,
|
||||
)
|
||||
from app.services.numbering import generate_complaint_no
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_complaints_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("complaint_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||
assert res.status_code == 200, res.text
|
||||
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
|
||||
|
||||
def test_generate_complaint_no_and_custom_prefix(db):
|
||||
dt = datetime(2026, 4, 15, 10, 0, tzinfo=timezone.utc)
|
||||
# Seed created CMP-2026-0001..0030 (when run in 2026) or current year; test custom prefix cleanly
|
||||
c1 = generate_complaint_no(db, "PHRC", dt)
|
||||
assert c1 == "PHRC-2026-0001"
|
||||
|
||||
# Existing CMP prefix in current KOLKATA year increments sequentially
|
||||
now_utc = datetime.now(timezone.utc)
|
||||
cur_year = now_utc.astimezone(KOLKATA).year
|
||||
next_cmp = generate_complaint_no(db, "CMP", now_utc)
|
||||
assert next_cmp == f"CMP-{cur_year}-0031"
|
||||
|
||||
|
||||
def test_response_time_and_downtime_calculations():
|
||||
reg = datetime(2026, 5, 10, 8, 0, tzinfo=timezone.utc)
|
||||
recv = datetime(2026, 5, 10, 8, 15, tzinfo=timezone.utc)
|
||||
att = datetime(2026, 5, 10, 9, 0, tzinfo=timezone.utc)
|
||||
rst = datetime(2026, 5, 10, 11, 30, tzinfo=timezone.utc)
|
||||
cls = datetime(2026, 5, 10, 12, 0, tzinfo=timezone.utc)
|
||||
ce_att = datetime(2026, 5, 10, 10, 0, tzinfo=timezone.utc)
|
||||
now = datetime(2026, 5, 10, 13, 0, tzinfo=timezone.utc)
|
||||
|
||||
# Response time
|
||||
assert compute_response_time_minutes(reg, recv, None, "registered_at") is None
|
||||
assert compute_response_time_minutes(reg, recv, att, "registered_at") == 60
|
||||
assert compute_response_time_minutes(reg, recv, att, "received_at") == 45
|
||||
|
||||
# CE response time
|
||||
assert compute_ce_response_time_minutes(reg, None) is None
|
||||
assert compute_ce_response_time_minutes(reg, ce_att) == 120
|
||||
|
||||
# Downtime milestones
|
||||
assert compute_downtime_minutes(reg, att, rst, cls, "attended_at", now) == (60, False)
|
||||
assert compute_downtime_minutes(reg, att, rst, cls, "restored_at", now) == (210, False)
|
||||
assert compute_downtime_minutes(reg, att, rst, cls, "closed_at", now) == (240, False)
|
||||
|
||||
# Ongoing downtime when chosen milestone is None
|
||||
assert compute_downtime_minutes(reg, att, None, None, "restored_at", now) == (300, True)
|
||||
|
||||
|
||||
def test_clip_downtime_to_month_across_boundary():
|
||||
# Jan 30 22:00 IST to Feb 02 04:00 IST
|
||||
start_utc = KOLKATA.localize(datetime(2026, 1, 30, 22, 0, 0)).astimezone(timezone.utc)
|
||||
end_utc = KOLKATA.localize(datetime(2026, 2, 2, 4, 0, 0)).astimezone(timezone.utc)
|
||||
|
||||
jan_mins, jan_days = clip_downtime_to_month(start_utc, end_utc, 2026, 1)
|
||||
assert jan_mins == 26 * 60 # 2h on Jan 30 + 24h on Jan 31 = 1560 mins
|
||||
assert jan_days == {date(2026, 1, 30), date(2026, 1, 31)}
|
||||
|
||||
feb_mins, feb_days = clip_downtime_to_month(start_utc, end_utc, 2026, 2)
|
||||
assert feb_mins == 28 * 60 # 24h on Feb 1 + 4h on Feb 2 = 1680 mins
|
||||
assert feb_days == {date(2026, 2, 1), date(2026, 2, 2)}
|
||||
|
||||
mar_mins, mar_days = clip_downtime_to_month(start_utc, end_utc, 2026, 3)
|
||||
assert mar_mins == 0
|
||||
assert mar_days == set()
|
||||
|
||||
|
||||
def test_complaint_field_level_permissions(client, db):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
ot = db.query(Department).filter(Department.code == "OT").first()
|
||||
icu_cmp = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.filter(Asset.department_id == icu.id, Complaint.call_status != "closed")
|
||||
.first()
|
||||
)
|
||||
ot_cmp = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.filter(Asset.department_id == ot.id)
|
||||
.first()
|
||||
)
|
||||
if icu_cmp is None:
|
||||
icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first()
|
||||
r = client.post(
|
||||
"/api/complaints",
|
||||
headers=dept_headers,
|
||||
json={"asset_id": icu_asset.id, "description": "Permission test issue", "priority": "non_critical"},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
icu_cmp_id = r.json()["id"]
|
||||
else:
|
||||
icu_cmp_id = icu_cmp.id
|
||||
|
||||
# Department scoping on list and detail
|
||||
if ot_cmp is not None:
|
||||
assert client.get(f"/api/complaints/{ot_cmp.id}", headers=dept_headers).status_code == 403
|
||||
assert client.get(f"/api/complaints/{ot_cmp.id}/events", headers=dept_headers).status_code == 403
|
||||
list_res = client.get("/api/complaints?page_size=200", headers=dept_headers)
|
||||
assert list_res.status_code == 200
|
||||
assert all(item["department_id"] == icu.id for item in list_res.json()["items"])
|
||||
|
||||
# Restricted technical fields rejected with 403 for dept_user, management, coordinator
|
||||
for headers in (dept_headers, mgmt_headers, coord_headers):
|
||||
for payload in (
|
||||
{"action_taken": "Replaced PCB"},
|
||||
{"root_cause": "Short circuit"},
|
||||
{"spare_required": True, "spare_cost_estimate": 5000},
|
||||
):
|
||||
r = client.patch(f"/api/complaints/{icu_cmp_id}", headers=headers, json=payload)
|
||||
assert r.status_code == 403
|
||||
assert r.json()["code"] == "FORBIDDEN_TECHNICAL_FIELDS"
|
||||
|
||||
# Non-restricted edit by dept_user works on own non-closed complaint, fails for mgmt/coord
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/complaints/{icu_cmp_id}",
|
||||
headers=dept_headers,
|
||||
json={"notes": "Updated ward note"},
|
||||
).status_code
|
||||
== 200
|
||||
)
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/complaints/{icu_cmp_id}",
|
||||
headers=mgmt_headers,
|
||||
json={"notes": "Mgmt edit"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/complaints/{icu_cmp_id}",
|
||||
headers=coord_headers,
|
||||
json={"notes": "Coord edit"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# biomedical and system_admin succeed on technical fields
|
||||
bio_patch = client.patch(
|
||||
f"/api/complaints/{icu_cmp_id}",
|
||||
headers=bio_headers,
|
||||
json={"action_taken": "Cleaned connector", "root_cause": "Loose cable"},
|
||||
)
|
||||
assert bio_patch.status_code == 200
|
||||
assert bio_patch.json()["action_taken"] == "Cleaned connector"
|
||||
|
||||
admin_patch = client.patch(
|
||||
f"/api/complaints/{icu_cmp_id}",
|
||||
headers=admin_headers,
|
||||
json={"corrective_action": "Secured latch"},
|
||||
)
|
||||
assert admin_patch.status_code == 200
|
||||
assert admin_patch.json()["corrective_action"] == "Secured latch"
|
||||
|
||||
|
||||
def test_full_complaint_workflow_and_asset_status_sync(client, db):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
asset = db.query(Asset).filter(Asset.department_id == icu.id, Asset.status == "in_service").first()
|
||||
assert asset is not None
|
||||
|
||||
bio1 = db.query(User).filter(User.email == "bio@poona.demo").first()
|
||||
bio2 = db.query(User).filter(User.email == "vikram.shinde@poona.demo").first()
|
||||
|
||||
# 1. Dept user raises critical complaint -> asset becomes under_repair
|
||||
create_res = client.post(
|
||||
"/api/complaints",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"description": "Ventilator pressure drop alarm",
|
||||
"breakdown_details": "Alarm triggered during patient weaning",
|
||||
"priority": "critical",
|
||||
"notes": "Urgent ICU support needed",
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
cmp_data = create_res.json()
|
||||
cid = cmp_data["id"]
|
||||
assert cmp_data["call_status"] == "open"
|
||||
assert cmp_data["asset_status"] == "under_repair"
|
||||
assert cmp_data["downtime_is_ongoing"] is True
|
||||
|
||||
# 2. Assign -> reassign (events logged)
|
||||
asg1 = client.post(
|
||||
f"/api/complaints/{cid}/assign",
|
||||
headers=bio_headers,
|
||||
json={"assigned_to_id": bio1.id, "note": "Initial assignment"},
|
||||
)
|
||||
assert asg1.status_code == 200
|
||||
assert asg1.json()["call_status"] == "in_progress"
|
||||
assert asg1.json()["assigned_to_id"] == bio1.id
|
||||
|
||||
asg2 = client.post(
|
||||
f"/api/complaints/{cid}/assign",
|
||||
headers=bio_headers,
|
||||
json={"assigned_to_id": bio2.id, "note": "Escalated to senior bio"},
|
||||
)
|
||||
assert asg2.status_code == 200
|
||||
assert asg2.json()["assigned_to_id"] == bio2.id
|
||||
|
||||
# 3. Attend -> response_time_minutes computed
|
||||
att_res = client.post(
|
||||
f"/api/complaints/{cid}/attend",
|
||||
headers=bio_headers,
|
||||
json={"attended_by_id": bio2.id, "note": "Reached ICU Bay"},
|
||||
)
|
||||
assert att_res.status_code == 200
|
||||
assert att_res.json()["attended_at"] is not None
|
||||
assert att_res.json()["response_time_minutes"] is not None
|
||||
|
||||
# 4. Edit technical / spare / CE fields
|
||||
ce_time = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
|
||||
tech_res = client.patch(
|
||||
f"/api/complaints/{cid}",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"action_taken": "Replaced inspiratory valve diaphragm",
|
||||
"root_cause": "Diaphragm tear",
|
||||
"corrective_action": "Replaced valve kit and ran leak test",
|
||||
"lessons_learned": "Inspect diaphragm at every 6m PM",
|
||||
"ce_name": "Mahesh Kulkarni (OEM)",
|
||||
"ce_attended_at": ce_time,
|
||||
"ce_action_taken": "Calibrated flow sensor post replacement",
|
||||
"spare_required": True,
|
||||
"spare_details": "Inspiratory valve diaphragm kit",
|
||||
"spare_cost_estimate": 12500.0,
|
||||
},
|
||||
)
|
||||
assert tech_res.status_code == 200
|
||||
assert tech_res.json()["spare_required"] is True
|
||||
assert tech_res.json()["ce_response_time_minutes"] is not None
|
||||
|
||||
# 5. Restore -> asset returns to in_service
|
||||
rst_res = client.post(
|
||||
f"/api/complaints/{cid}/restore",
|
||||
headers=bio_headers,
|
||||
json={"note": "Passed 30-min leak test"},
|
||||
)
|
||||
assert rst_res.status_code == 200
|
||||
assert rst_res.json()["restored_at"] is not None
|
||||
assert rst_res.json()["asset_status"] == "in_service"
|
||||
assert rst_res.json()["downtime_is_ongoing"] is False
|
||||
|
||||
# 6. Close -> call_status closed
|
||||
cls_res = client.post(
|
||||
f"/api/complaints/{cid}/close",
|
||||
headers=bio_headers,
|
||||
json={"closure_remarks": "Handed over to ICU charge nurse"},
|
||||
)
|
||||
assert cls_res.status_code == 200
|
||||
assert cls_res.json()["call_status"] == "closed"
|
||||
assert cls_res.json()["closed_at"] is not None
|
||||
assert cls_res.json()["asset_status"] == "in_service"
|
||||
|
||||
# 7. Reopen -> critical asset back to under_repair and restored_at cleared
|
||||
reopen_res = client.post(
|
||||
f"/api/complaints/{cid}/reopen",
|
||||
headers=bio_headers,
|
||||
json={"reason": "Alarm reappeared during shift change"},
|
||||
)
|
||||
assert reopen_res.status_code == 200
|
||||
assert reopen_res.json()["call_status"] == "in_progress"
|
||||
assert reopen_res.json()["closed_at"] is None
|
||||
assert reopen_res.json()["restored_at"] is None
|
||||
assert reopen_res.json()["downtime_is_ongoing"] is True
|
||||
assert reopen_res.json()["asset_status"] == "under_repair"
|
||||
|
||||
# 8. Correct timestamp: biomedical -> 403, system_admin -> 200
|
||||
new_reg = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
|
||||
bio_ts = client.post(
|
||||
f"/api/complaints/{cid}/correct-timestamp",
|
||||
headers=bio_headers,
|
||||
json={"field": "registered_at", "new_value": new_reg, "reason": "Late entry"},
|
||||
)
|
||||
assert bio_ts.status_code == 403
|
||||
|
||||
admin_ts = client.post(
|
||||
f"/api/complaints/{cid}/correct-timestamp",
|
||||
headers=admin_headers,
|
||||
json={"field": "registered_at", "new_value": new_reg, "reason": "Logged after phone call"},
|
||||
)
|
||||
assert admin_ts.status_code == 200
|
||||
assert admin_ts.json()["response_time_minutes"] >= 119
|
||||
|
||||
# 9. Verify events timeline
|
||||
ev_res = client.get(f"/api/complaints/{cid}/events", headers=bio_headers)
|
||||
assert ev_res.status_code == 200
|
||||
events = ev_res.json()["items"]
|
||||
event_types = [e["event_type"] for e in events]
|
||||
assert event_types == [
|
||||
"registered",
|
||||
"coverage_tagged",
|
||||
"assigned",
|
||||
"reassigned",
|
||||
"attended",
|
||||
"field_edited",
|
||||
"restored",
|
||||
"closed",
|
||||
"reopened",
|
||||
"timestamp_corrected",
|
||||
]
|
||||
assert events[3]["from_value"] == bio1.name
|
||||
assert events[3]["to_value"] == bio2.name
|
||||
assert events[9]["note"] == "registered_at: Logged after phone call"
|
||||
|
||||
|
||||
def test_require_closure_remarks_and_wired_settings(client, db):
|
||||
from datetime import date
|
||||
from app.services.calculations import compute_sla_status
|
||||
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
asset = db.query(Asset).first()
|
||||
assert asset is not None
|
||||
|
||||
# Create a complaint to test close with require_closure_remarks True vs False
|
||||
c_res = client.post(
|
||||
"/api/complaints",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"description": "Display backlight flicker",
|
||||
"priority": "non_critical",
|
||||
},
|
||||
)
|
||||
assert c_res.status_code == 201
|
||||
cid = c_res.json()["id"]
|
||||
assert c_res.json()["sla_target_hours"] == 24
|
||||
assert c_res.json()["sla_breached"] is False
|
||||
|
||||
# Default require_closure_remarks=True -> blank remarks returns 422 CLOSURE_REMARKS_REQUIRED
|
||||
fail_close = client.post(
|
||||
f"/api/complaints/{cid}/close",
|
||||
headers=bio_headers,
|
||||
json={"closure_remarks": " "},
|
||||
)
|
||||
assert fail_close.status_code == 422
|
||||
assert fail_close.json()["code"] == "CLOSURE_REMARKS_REQUIRED"
|
||||
assert fail_close.json()["detail"] == "Closure remarks are required."
|
||||
|
||||
try:
|
||||
# Disable require_closure_remarks -> blank remarks closes cleanly (200)
|
||||
upd = client.put(
|
||||
"/api/settings",
|
||||
headers=admin_headers,
|
||||
json={"values": {"require_closure_remarks": False}},
|
||||
)
|
||||
assert upd.status_code == 200
|
||||
|
||||
ok_close = client.post(
|
||||
f"/api/complaints/{cid}/close",
|
||||
headers=bio_headers,
|
||||
json={"closure_remarks": ""},
|
||||
)
|
||||
assert ok_close.status_code == 200
|
||||
assert ok_close.json()["call_status"] == "closed"
|
||||
|
||||
# Verify default_pm_mode setting when service_mode is omitted on POST /api/pm/schedules
|
||||
pm_res = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"frequency_months": 6,
|
||||
"responsible_team": "Biomedical Team",
|
||||
"next_planned_date": str(date.today()),
|
||||
},
|
||||
)
|
||||
assert pm_res.status_code == 201, pm_res.text
|
||||
assert pm_res.json()["service_mode"] == "in_house"
|
||||
finally:
|
||||
client.put(
|
||||
"/api/settings",
|
||||
headers=admin_headers,
|
||||
json={"values": {"require_closure_remarks": True}},
|
||||
)
|
||||
|
||||
# Pure unit test for compute_sla_status using injected SLA settings
|
||||
t0 = datetime(2026, 6, 1, 8, 0, tzinfo=timezone.utc)
|
||||
breached, target = compute_sla_status(
|
||||
"critical", t0, None, None, critical_sla_hours=4, non_critical_sla_hours=24, now_utc=t0 + timedelta(hours=5)
|
||||
)
|
||||
assert target == 4 and breached is True
|
||||
not_breached, target2 = compute_sla_status(
|
||||
"non_critical", t0, None, None, critical_sla_hours=4, non_critical_sla_hours=24, now_utc=t0 + timedelta(hours=5)
|
||||
)
|
||||
assert target2 == 24 and not_breached is False
|
||||
|
||||
|
||||
def test_close_without_restore_sets_restored_at_and_reopen_recloses(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
asset = db.query(Asset).first()
|
||||
assert asset is not None
|
||||
|
||||
create_res = client.post(
|
||||
"/api/complaints",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"priority": "non_critical",
|
||||
"description": "Close without explicit restore check",
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
cid = create_res.json()["id"]
|
||||
|
||||
# Close directly without /restore -> restored_at is backfilled to closed_at
|
||||
close1 = client.post(
|
||||
f"/api/complaints/{cid}/close",
|
||||
headers=bio_headers,
|
||||
json={"closure_remarks": "Resolved during inspection"},
|
||||
)
|
||||
assert close1.status_code == 200, close1.text
|
||||
c1 = close1.json()
|
||||
assert c1["call_status"] == "closed"
|
||||
assert c1["closed_at"] is not None
|
||||
assert c1["restored_at"] == c1["closed_at"]
|
||||
assert c1["downtime_is_ongoing"] is False
|
||||
|
||||
# Reopen -> restored_at is cleared and downtime is ongoing again
|
||||
reopen1 = client.post(
|
||||
f"/api/complaints/{cid}/reopen",
|
||||
headers=bio_headers,
|
||||
json={"reason": "Issue recurred"},
|
||||
)
|
||||
assert reopen1.status_code == 200, reopen1.text
|
||||
r1 = reopen1.json()
|
||||
assert r1["call_status"] != "closed"
|
||||
assert r1["restored_at"] is None
|
||||
assert r1["closed_at"] is None
|
||||
assert r1["downtime_is_ongoing"] is True
|
||||
|
||||
# Close again without /restore -> restored_at == closed_at again
|
||||
close2 = client.post(
|
||||
f"/api/complaints/{cid}/close",
|
||||
headers=bio_headers,
|
||||
json={"closure_remarks": "Replaced cable and verified"},
|
||||
)
|
||||
assert close2.status_code == 200, close2.text
|
||||
c2 = close2.json()
|
||||
assert c2["closed_at"] is not None
|
||||
assert c2["restored_at"] == c2["closed_at"]
|
||||
assert c2["downtime_is_ongoing"] is False
|
||||
|
||||
|
||||
def test_sla_breach_alert_emitted_and_suppressed_when_restored(client, db):
|
||||
from app.core.time_utils import effective_now_utc
|
||||
from app.models import Notification
|
||||
from app.services.alerts import run_alert_check
|
||||
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
asset = db.query(Asset).first()
|
||||
assert asset is not None
|
||||
|
||||
r_unrestored = client.post(
|
||||
"/api/complaints",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"priority": "critical",
|
||||
"description": "SLA breach unrestored test",
|
||||
},
|
||||
)
|
||||
r_restored = client.post(
|
||||
"/api/complaints",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"priority": "critical",
|
||||
"description": "SLA breach already restored test",
|
||||
},
|
||||
)
|
||||
assert r_unrestored.status_code == 201 and r_restored.status_code == 201
|
||||
cid_unrestored = r_unrestored.json()["id"]
|
||||
cid_restored = r_restored.json()["id"]
|
||||
|
||||
now = effective_now_utc(db)
|
||||
past_5h = now - timedelta(hours=5)
|
||||
try:
|
||||
c_unrestored = db.query(Complaint).filter(Complaint.id == cid_unrestored).first()
|
||||
c_restored = db.query(Complaint).filter(Complaint.id == cid_restored).first()
|
||||
c_unrestored.registered_at = past_5h
|
||||
c_unrestored.restored_at = None
|
||||
c_restored.registered_at = past_5h
|
||||
c_restored.restored_at = now - timedelta(hours=1)
|
||||
db.commit()
|
||||
|
||||
run_alert_check(db)
|
||||
db.commit()
|
||||
|
||||
sla_unrestored = (
|
||||
db.query(Notification)
|
||||
.filter(
|
||||
Notification.type == "sla_breach",
|
||||
Notification.entity_type == "complaint",
|
||||
Notification.entity_id == cid_unrestored,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
assert len(sla_unrestored) == 1
|
||||
assert "SLA Breach: Open > 4h" in sla_unrestored[0].title
|
||||
|
||||
# Restored complaint past SLA should NOT emit sla_breach
|
||||
sla_restored = (
|
||||
db.query(Notification)
|
||||
.filter(
|
||||
Notification.type == "sla_breach",
|
||||
Notification.entity_type == "complaint",
|
||||
Notification.entity_id == cid_restored,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
assert sla_restored == []
|
||||
|
||||
# 5h open is < default escalation_open_complaint_hours (24h), so critical_complaint stays silent
|
||||
crit_unrestored = (
|
||||
db.query(Notification)
|
||||
.filter(
|
||||
Notification.type == "critical_complaint",
|
||||
Notification.entity_type == "complaint",
|
||||
Notification.entity_id == cid_unrestored,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
assert crit_unrestored == []
|
||||
|
||||
# When open > 24h, unrestored complaint triggers critical_complaint alert,
|
||||
# but restored complaint does NOT trigger it even if not closed yet
|
||||
past_26h = now - timedelta(hours=26)
|
||||
c_unrestored.registered_at = past_26h
|
||||
c_restored.registered_at = past_26h
|
||||
db.commit()
|
||||
run_alert_check(db)
|
||||
db.commit()
|
||||
|
||||
crit_unrestored_26h = (
|
||||
db.query(Notification)
|
||||
.filter(
|
||||
Notification.type == "critical_complaint",
|
||||
Notification.entity_type == "complaint",
|
||||
Notification.entity_id == cid_unrestored,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
assert len(crit_unrestored_26h) == 1
|
||||
assert "Critical Complaint Open > 24h" in crit_unrestored_26h[0].title
|
||||
|
||||
crit_restored_26h = (
|
||||
db.query(Notification)
|
||||
.filter(
|
||||
Notification.type == "critical_complaint",
|
||||
Notification.entity_type == "complaint",
|
||||
Notification.entity_id == cid_restored,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
assert crit_restored_26h == []
|
||||
finally:
|
||||
db.query(Notification).filter(
|
||||
Notification.entity_type == "complaint",
|
||||
Notification.entity_id.in_([cid_unrestored, cid_restored]),
|
||||
).delete(synchronize_session=False)
|
||||
db.commit()
|
||||
for cid_cleanup in (cid_unrestored, cid_restored):
|
||||
client.post(
|
||||
f"/api/complaints/{cid_cleanup}/close",
|
||||
headers=bio_headers,
|
||||
json={"closure_remarks": "Cleanup after SLA alert test"},
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
from io import BytesIO
|
||||
from datetime import date, timedelta
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import Asset, Department, Location, PMRecord, PMSchedule, Vendor
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def _seed(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("uploads")
|
||||
seed_database(db, upload_dir=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
|
||||
token = res.json()["access_token"]
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def test_pm_record_attachment_upload_and_download(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
pm_rec = db.query(PMRecord).first()
|
||||
assert pm_rec is not None
|
||||
|
||||
# Valid PDF file upload against pm_record
|
||||
fake_pdf = b"%PDF-1.4 sample pm service report job sheet content"
|
||||
files = {"file": ("pm_service_report.pdf", BytesIO(fake_pdf), "application/pdf")}
|
||||
data = {"entity_type": "pm_record", "entity_id": str(pm_rec.id)}
|
||||
|
||||
upload_res = client.post("/api/attachments", headers=bio_headers, data=data, files=files)
|
||||
assert upload_res.status_code == 201, upload_res.text
|
||||
att_data = upload_res.json()
|
||||
att_id = att_data["id"]
|
||||
assert att_data["entity_type"] == "pm_record"
|
||||
assert att_data["original_name"] == "pm_service_report.pdf"
|
||||
|
||||
# List attachments for pm_record
|
||||
list_res = client.get(
|
||||
f"/api/attachments?entity_type=pm_record&entity_id={pm_rec.id}",
|
||||
headers=bio_headers,
|
||||
)
|
||||
assert list_res.status_code == 200
|
||||
assert any(item["id"] == att_id for item in list_res.json()["items"])
|
||||
|
||||
# Download attachment
|
||||
dl_res = client.get(f"/api/attachments/{att_id}/download", headers=bio_headers)
|
||||
assert dl_res.status_code == 200
|
||||
assert dl_res.content == fake_pdf
|
||||
|
||||
|
||||
def test_complaint_assigned_team_and_location_filter(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
asset = db.query(Asset).filter(Asset.location_id.isnot(None)).first()
|
||||
assert asset is not None
|
||||
|
||||
# 1. Raise complaint with assigned_team
|
||||
res = client.post(
|
||||
"/api/complaints",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"description": "Ventilator screen flickering",
|
||||
"priority": "non_critical",
|
||||
"assigned_team": "Biomedical Clinical Support",
|
||||
},
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
c_data = res.json()
|
||||
cid = c_data["id"]
|
||||
assert c_data["assigned_team"] == "Biomedical Clinical Support"
|
||||
|
||||
# 2. Assign team via /assign endpoint
|
||||
assign_res = client.post(
|
||||
f"/api/complaints/{cid}/assign",
|
||||
headers=bio_headers,
|
||||
json={"assigned_team": "External Vendor Tier 2 Team", "note": "Assigned to specialized vendor team"},
|
||||
)
|
||||
assert assign_res.status_code == 200, assign_res.text
|
||||
assert assign_res.json()["assigned_team"] == "External Vendor Tier 2 Team"
|
||||
|
||||
# 3. Filter by location_id
|
||||
loc_res = client.get(
|
||||
f"/api/complaints?location_id={asset.location_id}",
|
||||
headers=bio_headers,
|
||||
)
|
||||
assert loc_res.status_code == 200
|
||||
items = loc_res.json()["items"]
|
||||
assert any(c["id"] == cid for c in items)
|
||||
|
||||
|
||||
def test_demo_equipment_serial_no(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept = db.query(Department).first()
|
||||
vendor = db.query(Vendor).first()
|
||||
today = effective_today(db)
|
||||
|
||||
# Create demo equipment with serial_no
|
||||
res = client.post(
|
||||
"/api/demo-equipment",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"name": "Trial Dialysis Unit",
|
||||
"equipment_type": "Dialysis",
|
||||
"serial_no": "DEMO-SN-DIAL-901",
|
||||
"supplier_id": vendor.id,
|
||||
"department_id": dept.id,
|
||||
"start_date": str(today),
|
||||
"expected_return_date": str(today + timedelta(days=14)),
|
||||
"remarks": "Evaluation unit on 14-day trial",
|
||||
},
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
demo_data = res.json()
|
||||
demo_id = demo_data["id"]
|
||||
assert demo_data["serial_no"] == "DEMO-SN-DIAL-901"
|
||||
|
||||
# List demo equipment
|
||||
list_res = client.get(f"/api/demo-equipment?department_id={dept.id}", headers=bio_headers)
|
||||
assert list_res.status_code == 200
|
||||
found = next((item for item in list_res.json()["items"] if item["id"] == demo_id), None)
|
||||
assert found is not None
|
||||
assert found["serial_no"] == "DEMO-SN-DIAL-901"
|
||||
|
||||
|
||||
def test_department_visit_new_requirements_and_monthly_report(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
dept = db.query(Department).first()
|
||||
today = effective_today(db)
|
||||
|
||||
# Create visit with new_requirements
|
||||
req_text = "Urgent: Requesting 2 additional Infusion Pumps for Bed 3 & 4"
|
||||
res = client.post(
|
||||
"/api/visits",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"department_id": dept.id,
|
||||
"visit_date": str(today),
|
||||
"observations": "All ICU ventilators functioning normally; routine checks complete.",
|
||||
"new_requirements": req_text,
|
||||
},
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
v_data = res.json()
|
||||
assert v_data["new_requirements"] == req_text
|
||||
|
||||
# Monthly Department Report reflects new requirements
|
||||
month_str = today.strftime("%Y-%m")
|
||||
rep_res = client.get(
|
||||
f"/api/reports/monthly-department?month={month_str}&department_id={dept.id}",
|
||||
headers=mgmt_headers,
|
||||
)
|
||||
assert rep_res.status_code == 200, rep_res.text
|
||||
rows = rep_res.json()["rows"]
|
||||
dept_row = next((r for r in rows if r["department_id"] == dept.id), None)
|
||||
assert dept_row is not None
|
||||
assert req_text in dept_row["new_equipment_requirements"]
|
||||
|
||||
|
||||
def test_asset_calibration_and_insurance_filters(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
# Filter calibration applicable
|
||||
res_cal_yes = client.get("/api/assets?requires_calibration=true", headers=bio_headers)
|
||||
assert res_cal_yes.status_code == 200
|
||||
for a in res_cal_yes.json()["items"]:
|
||||
assert a["requires_calibration"] is True
|
||||
|
||||
res_cal_no = client.get("/api/assets?requires_calibration=false", headers=bio_headers)
|
||||
assert res_cal_no.status_code == 200
|
||||
for a in res_cal_no.json()["items"]:
|
||||
assert a["requires_calibration"] is False
|
||||
|
||||
# Filter insurance applicable
|
||||
res_ins_yes = client.get("/api/assets?insurance_applicable=true", headers=bio_headers)
|
||||
assert res_ins_yes.status_code == 200
|
||||
for a in res_ins_yes.json()["items"]:
|
||||
assert a["insurance_applicable"] is True
|
||||
|
||||
|
||||
def test_bulk_import_templates_endpoints(client):
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
|
||||
# Contracts template
|
||||
r_c = client.get("/api/contracts/import-template", headers=coord_headers)
|
||||
assert r_c.status_code == 200
|
||||
assert r_c.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
assert len(r_c.content) > 1000
|
||||
|
||||
# Calibration template
|
||||
r_cal = client.get("/api/calibration/import-template", headers=coord_headers)
|
||||
assert r_cal.status_code == 200
|
||||
assert r_cal.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
assert len(r_cal.content) > 1000
|
||||
|
||||
# Insurance template
|
||||
r_ins = client.get("/api/insurance/import-template", headers=coord_headers)
|
||||
assert r_ins.status_code == 200
|
||||
assert r_ins.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
assert len(r_ins.content) > 1000
|
||||
|
||||
|
||||
def test_sqlite_auto_migration_reconciles_missing_columns():
|
||||
from sqlalchemy import create_engine
|
||||
from app.core.migrations import run_sqlite_migrations
|
||||
|
||||
test_eng = create_engine("sqlite:///:memory:")
|
||||
with test_eng.begin() as conn:
|
||||
# Create complaints table without assigned_team column
|
||||
conn.exec_driver_sql(
|
||||
"CREATE TABLE complaints ("
|
||||
"id INTEGER PRIMARY KEY, "
|
||||
"complaint_no VARCHAR(50), "
|
||||
"asset_id INTEGER, "
|
||||
"description TEXT, "
|
||||
"priority VARCHAR(50), "
|
||||
"registered_at DATETIME, "
|
||||
"registered_by_id INTEGER, "
|
||||
"received_by_id INTEGER, "
|
||||
"call_status VARCHAR(50)"
|
||||
")"
|
||||
)
|
||||
cols_before = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()}
|
||||
assert "assigned_team" not in cols_before
|
||||
|
||||
# Run auto-migration
|
||||
run_sqlite_migrations(test_eng)
|
||||
|
||||
with test_eng.begin() as conn:
|
||||
cols_after = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()}
|
||||
assert "assigned_team" in cols_after
|
||||
@@ -0,0 +1,7 @@
|
||||
def test_health_check(client):
|
||||
response = client.get("/api/health")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "ok"
|
||||
assert data["service"] == "Poona Hospital AMS"
|
||||
assert data["version"] == "0.1.0"
|
||||
@@ -0,0 +1,148 @@
|
||||
from datetime import timedelta
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import Asset, Complaint, Department, Notification
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.alerts import run_alert_check
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_phase6_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("phase6_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||
assert res.status_code == 200, res.text
|
||||
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
|
||||
|
||||
def test_alert_check_dedupe_and_seed_notifications(db):
|
||||
# seed_database already ran run_alert_check -> notifications exist in DB
|
||||
initial_count = db.query(Notification).count()
|
||||
assert initial_count > 0
|
||||
|
||||
# Running run_alert_check again immediately creates 0 duplicates
|
||||
res2 = run_alert_check(db)
|
||||
db.commit()
|
||||
assert res2["created"] == 0
|
||||
assert db.query(Notification).count() == initial_count
|
||||
|
||||
|
||||
def test_demo_clock_alert_run_and_admin_only_permission(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
|
||||
# Non-admins get 403 on POST /api/alerts/run
|
||||
for h in (bio_headers, dept_headers, mgmt_headers, coord_headers):
|
||||
assert client.post("/api/alerts/run", headers=h).status_code == 403
|
||||
|
||||
base_today = effective_today(db)
|
||||
future_date = base_today + timedelta(days=20)
|
||||
|
||||
try:
|
||||
set_res = client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": str(future_date)},
|
||||
)
|
||||
assert set_res.status_code == 200
|
||||
|
||||
# First run at +20 days creates new notifications for newly-entered windows
|
||||
run1 = client.post("/api/alerts/run", headers=admin_headers)
|
||||
assert run1.status_code == 200, run1.text
|
||||
data1 = run1.json()
|
||||
assert data1["evaluated_today"] == str(future_date)
|
||||
assert data1["created"] > 0
|
||||
|
||||
# Second run at same +20 days creates 0 (dedupe)
|
||||
run2 = client.post("/api/alerts/run", headers=admin_headers)
|
||||
assert run2.status_code == 200
|
||||
assert run2.json()["created"] == 0
|
||||
finally:
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": None},
|
||||
)
|
||||
|
||||
|
||||
def test_per_user_read_state_and_department_scoping(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
admin_list_before = client.get("/api/notifications?limit=100", headers=admin_headers).json()
|
||||
bio_list_before = client.get("/api/notifications?limit=100", headers=bio_headers).json()
|
||||
assert admin_list_before["unread_count"] > 0
|
||||
assert bio_list_before["unread_count"] > 0
|
||||
|
||||
# Pick a calibration_due notification visible to both admin and bio
|
||||
cal_items = [n for n in admin_list_before["items"] if n["type"] == "calibration_due"]
|
||||
assert len(cal_items) > 0
|
||||
target_id = cal_items[0]["id"]
|
||||
assert cal_items[0]["link_url"] == "/calibration"
|
||||
|
||||
# Admin marks single notification as read -> bio still sees it unread
|
||||
mark_res = client.post(f"/api/notifications/{target_id}/read", headers=admin_headers)
|
||||
assert mark_res.status_code == 200
|
||||
assert mark_res.json()["is_read"] is True
|
||||
|
||||
admin_after_one = client.get("/api/notifications?limit=100", headers=admin_headers).json()
|
||||
bio_after_one = client.get("/api/notifications?limit=100", headers=bio_headers).json()
|
||||
assert admin_after_one["unread_count"] == admin_list_before["unread_count"] - 1
|
||||
assert bio_after_one["unread_count"] == bio_list_before["unread_count"]
|
||||
|
||||
# Admin marks all calibration_due notifications read -> unread_calibration_count becomes 0 for admin, unchanged for bio
|
||||
mark_cal = client.post("/api/notifications/read-all?type=calibration_due", headers=admin_headers)
|
||||
assert mark_cal.status_code == 200
|
||||
admin_after_cal = client.get("/api/notifications?limit=100", headers=admin_headers).json()
|
||||
bio_after_cal = client.get("/api/notifications?limit=100", headers=bio_headers).json()
|
||||
assert admin_after_cal["unread_calibration_count"] == 0
|
||||
assert bio_after_cal["unread_calibration_count"] > 0
|
||||
|
||||
# department_user only sees critical_complaint alerts for their own department (ICU)
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
dept_notifs = client.get("/api/notifications?limit=100", headers=dept_headers).json()
|
||||
for n in dept_notifs["items"]:
|
||||
assert n["entity_type"] == "complaint"
|
||||
assert n["link_url"] == f"/complaints/{n['entity_id']}"
|
||||
comp = db.query(Complaint).filter(Complaint.id == n["entity_id"]).first()
|
||||
assert comp.asset.department_id == icu.id
|
||||
|
||||
|
||||
def test_dashboard_summary_role_scoping_and_charts(client, db):
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
icu_asset_count = db.query(Asset).filter(Asset.department_id == icu.id).count()
|
||||
total_asset_count = db.query(Asset).count()
|
||||
|
||||
mgmt_res = client.get("/api/dashboard/summary", headers=mgmt_headers)
|
||||
assert mgmt_res.status_code == 200, mgmt_res.text
|
||||
mgmt = mgmt_res.json()
|
||||
assert mgmt["department_scope"] is None
|
||||
assert mgmt["kpis"]["total_assets"] == total_asset_count
|
||||
assert len(mgmt["monthly_downtime_trend"]) == 6
|
||||
assert len(mgmt["pm_planned_vs_completed"]) == 6
|
||||
assert len(mgmt["complaints_by_status"]) == 3
|
||||
assert len(mgmt["complaints_by_department"]) >= 2
|
||||
assert len(mgmt["recent_complaints"]) <= 8
|
||||
|
||||
dept_res = client.get("/api/dashboard/summary", headers=dept_headers)
|
||||
assert dept_res.status_code == 200, dept_res.text
|
||||
dept = dept_res.json()
|
||||
assert dept["department_scope"] == icu.name
|
||||
assert dept["kpis"]["total_assets"] == icu_asset_count
|
||||
assert dept["kpis"]["total_assets"] < mgmt["kpis"]["total_assets"]
|
||||
assert len(dept["monthly_downtime_trend"]) == 6
|
||||
assert len(dept["pm_planned_vs_completed"]) == 6
|
||||
assert [d["department"] for d in dept["complaints_by_department"]] == [icu.name]
|
||||
assert all(rc["department_name"] == icu.name for rc in dept["recent_complaints"])
|
||||
@@ -0,0 +1,397 @@
|
||||
from datetime import date, timedelta
|
||||
import io
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import Asset, Category, Complaint, Contract, Department, Location, Vendor
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_phase5_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("phase5_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 _make_png_bytes() -> bytes:
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (16, 16), color=(20, 90, 160)).save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_contract_create_renew_supersede_history_and_scoping(client, db):
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
ot = db.query(Department).filter(Department.code == "OT").first()
|
||||
icu_loc = db.query(Location).filter(Location.department_id == icu.id).first()
|
||||
cat = db.query(Category).first()
|
||||
provider = db.query(Vendor).filter(Vendor.vendor_type == "service_provider").first()
|
||||
|
||||
# Dedicated asset in ICU for deterministic renewal chain check
|
||||
asset_res = client.post(
|
||||
"/api/assets",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_code": "PHRC-CON-001",
|
||||
"serial_no": "SN-CON-001",
|
||||
"name": "Contract Renewal Test Ventilator",
|
||||
"category_id": cat.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": icu_loc.id,
|
||||
"status": "in_service",
|
||||
"criticality": "critical",
|
||||
},
|
||||
)
|
||||
assert asset_res.status_code == 201
|
||||
asset_id = asset_res.json()["id"]
|
||||
|
||||
# department_user cannot create contracts
|
||||
assert (
|
||||
client.post(
|
||||
"/api/contracts",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"contract_type": "AMC",
|
||||
"provider_id": provider.id,
|
||||
"start_date": "2025-01-01",
|
||||
"end_date": "2025-12-31",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# Coordinator creates initial contract
|
||||
c1_res = client.post(
|
||||
"/api/contracts",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"contract_type": "AMC",
|
||||
"provider_id": provider.id,
|
||||
"start_date": "2025-01-01",
|
||||
"end_date": "2025-12-31",
|
||||
"coverage_period_text": "1 Year",
|
||||
"remarks": "Initial AMC",
|
||||
},
|
||||
)
|
||||
assert c1_res.status_code == 201, c1_res.text
|
||||
c1 = c1_res.json()
|
||||
assert c1["is_superseded"] is False
|
||||
|
||||
# Renew contract -> Note N1: old_contract.is_superseded=True, new_contract.renewed_from_id=c1.id
|
||||
renew_res = client.post(
|
||||
f"/api/contracts/{c1['id']}/renew",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"contract_type": "CMC",
|
||||
"start_date": "2026-01-01",
|
||||
"end_date": "2026-12-31",
|
||||
"coverage_period_text": "1 Year Comprehensive",
|
||||
"remarks": "Upgraded to CMC",
|
||||
},
|
||||
)
|
||||
assert renew_res.status_code == 200, renew_res.text
|
||||
rj = renew_res.json()
|
||||
assert rj["old_contract"]["id"] == c1["id"]
|
||||
assert rj["old_contract"]["is_superseded"] is True
|
||||
assert rj["old_contract"]["status"] == "superseded"
|
||||
assert rj["new_contract"]["renewed_from_id"] == c1["id"]
|
||||
assert rj["new_contract"]["is_superseded"] is False
|
||||
assert rj["new_contract"]["contract_type"] == "CMC"
|
||||
|
||||
# History returns both contracts newest first
|
||||
hist_res = client.get(f"/api/contracts/history/{asset_id}", headers=dept_headers)
|
||||
assert hist_res.status_code == 200
|
||||
hist_items = hist_res.json()["items"]
|
||||
assert len(hist_items) == 2
|
||||
assert hist_items[0]["id"] == rj["new_contract"]["id"]
|
||||
assert hist_items[1]["id"] == c1["id"]
|
||||
assert hist_items[1]["is_superseded"] is True
|
||||
|
||||
# include_superseded=false hides superseded contract
|
||||
active_only = client.get(
|
||||
f"/api/contracts?asset_id={asset_id}&include_superseded=false",
|
||||
headers=coord_headers,
|
||||
).json()
|
||||
assert active_only["total"] == 1
|
||||
assert active_only["items"][0]["id"] == rj["new_contract"]["id"]
|
||||
|
||||
# department_user gets 403 on another department's asset history and list only returns ICU
|
||||
ot_asset = db.query(Asset).filter(Asset.department_id == ot.id).first()
|
||||
assert client.get(f"/api/contracts/history/{ot_asset.id}", headers=dept_headers).status_code == 403
|
||||
dept_list = client.get("/api/contracts", headers=dept_headers).json()["items"]
|
||||
assert all(item["department_id"] == icu.id for item in dept_list)
|
||||
|
||||
|
||||
def test_warranty_and_insurance_expiry_and_permissions(client, db):
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first()
|
||||
insurer = db.query(Vendor).filter(Vendor.vendor_type == "insurer").first()
|
||||
today = effective_today(db)
|
||||
|
||||
# department_user cannot write warranty or insurance
|
||||
assert (
|
||||
client.post(
|
||||
"/api/warranties",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_id": icu_asset.id,
|
||||
"duration_months": 12,
|
||||
"start_date": str(today - timedelta(days=30)),
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.post(
|
||||
"/api/insurance",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_id": icu_asset.id,
|
||||
"insurer_id": insurer.id,
|
||||
"policy_no": "POL-DENIED",
|
||||
"start_date": str(today),
|
||||
"end_date": str(today + timedelta(days=365)),
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# Coordinator creates expiring warranty (ends in 5 days -> expiring, red)
|
||||
w_start = today - timedelta(days=360)
|
||||
w_end = today + timedelta(days=5)
|
||||
w_res = client.post(
|
||||
"/api/warranties",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"asset_id": icu_asset.id,
|
||||
"duration_months": 12,
|
||||
"start_date": str(w_start),
|
||||
"end_date": str(w_end),
|
||||
"provider_id": icu_asset.supplier_id,
|
||||
"remarks": "Expiring warranty check",
|
||||
},
|
||||
)
|
||||
assert w_res.status_code == 201, w_res.text
|
||||
wj = w_res.json()
|
||||
assert wj["status"] == "expiring"
|
||||
assert wj["severity"] == "red"
|
||||
assert wj["days_to_expiry"] == 5
|
||||
|
||||
# Coordinator creates expired insurance policy (ended yesterday -> expired, red)
|
||||
ins_res = client.post(
|
||||
"/api/insurance",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"asset_id": icu_asset.id,
|
||||
"insurer_id": insurer.id,
|
||||
"policy_no": "PHRC-POL-TEST-99",
|
||||
"start_date": str(today - timedelta(days=366)),
|
||||
"end_date": str(today - timedelta(days=1)),
|
||||
"coverage_amount": 450000.0,
|
||||
"remarks": "Expired policy check",
|
||||
},
|
||||
)
|
||||
assert ins_res.status_code == 201, ins_res.text
|
||||
ij = ins_res.json()
|
||||
assert ij["status"] == "expired"
|
||||
assert ij["severity"] == "red"
|
||||
assert ij["days_to_expiry"] == -1
|
||||
|
||||
# Upload attachment to insurance -> attachment_count increments to 1
|
||||
up = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "insurance", "entity_id": str(ij["id"])},
|
||||
files={"file": ("policy.png", _make_png_bytes(), "image/png")},
|
||||
)
|
||||
assert up.status_code == 201
|
||||
fetched = client.get(f"/api/insurance?asset_id={icu_asset.id}", headers=coord_headers).json()["items"]
|
||||
matched = [x for x in fetched if x["id"] == ij["id"]][0]
|
||||
assert matched["attachment_count"] == 1
|
||||
|
||||
|
||||
def test_demo_equipment_overdue_detection_and_return(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
icu_loc = db.query(Location).filter(Location.department_id == icu.id).first()
|
||||
supplier = db.query(Vendor).filter(Vendor.vendor_type == "supplier").first()
|
||||
|
||||
# department_user gets 403 on write
|
||||
assert (
|
||||
client.post(
|
||||
"/api/demo-equipment",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"name": "Unauthorized Demo",
|
||||
"equipment_type": "Monitor",
|
||||
"supplier_id": supplier.id,
|
||||
"department_id": icu.id,
|
||||
"start_date": "2028-01-01",
|
||||
"expected_return_date": "2028-01-10",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
create_res = client.post(
|
||||
"/api/demo-equipment",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"name": "Demo Transport Ventilator X2",
|
||||
"equipment_type": "Ventilator",
|
||||
"supplier_id": supplier.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": icu_loc.id,
|
||||
"start_date": "2028-04-01",
|
||||
"expected_return_date": "2028-04-15",
|
||||
"remarks": "Clinical trial in ICU",
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
demo_id = create_res.json()["id"]
|
||||
|
||||
try:
|
||||
# 1) Set demo_as_of_date = 2028-04-13 (2 days left -> on_demo, yellow)
|
||||
client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": "2028-04-13"})
|
||||
r1 = [x for x in client.get("/api/demo-equipment", headers=coord_headers).json()["items"] if x["id"] == demo_id][0]
|
||||
assert r1["status"] == "on_demo"
|
||||
assert r1["severity"] == "yellow"
|
||||
assert r1["days_remaining"] == 2
|
||||
|
||||
# 2) Set demo_as_of_date = 2028-04-20 (past expected_return_date -> overdue_return, red, days_remaining=-5)
|
||||
client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": "2028-04-20"})
|
||||
r2 = [x for x in client.get("/api/demo-equipment?status=overdue_return", headers=coord_headers).json()["items"] if x["id"] == demo_id][0]
|
||||
assert r2["status"] == "overdue_return"
|
||||
assert r2["severity"] == "red"
|
||||
assert r2["days_remaining"] == -5
|
||||
|
||||
# 3) Mark returned on 2028-04-18 -> status='returned', severity='ok'
|
||||
ret_res = client.post(
|
||||
f"/api/demo-equipment/{demo_id}/return",
|
||||
headers=coord_headers,
|
||||
json={"actual_return_date": "2028-04-18", "remarks": "Picked up by vendor."},
|
||||
)
|
||||
assert ret_res.status_code == 200, ret_res.text
|
||||
rj = ret_res.json()
|
||||
assert rj["status"] == "returned"
|
||||
assert rj["severity"] == "ok"
|
||||
assert rj["actual_return_date"] == "2028-04-18"
|
||||
finally:
|
||||
client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": None})
|
||||
|
||||
|
||||
def test_department_visits_permissions_and_multi_linking(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
icu_assets = db.query(Asset).filter(Asset.department_id == icu.id).limit(2).all()
|
||||
complaints = db.query(Complaint).limit(3).all()
|
||||
assert len(icu_assets) >= 2 and len(complaints) >= 3
|
||||
|
||||
# department_user and coordinator get 403 on GET and POST
|
||||
assert client.get("/api/visits", headers=dept_headers).status_code == 403
|
||||
assert client.get("/api/visits", headers=coord_headers).status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/visits",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"department_id": icu.id,
|
||||
"visit_date": "2026-05-10",
|
||||
"observations": "Coordinator denied",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# management can GET (200) but gets 403 on POST
|
||||
assert client.get("/api/visits", headers=mgmt_headers).status_code == 200
|
||||
assert (
|
||||
client.post(
|
||||
"/api/visits",
|
||||
headers=mgmt_headers,
|
||||
json={
|
||||
"department_id": icu.id,
|
||||
"visit_date": "2026-05-10",
|
||||
"observations": "Mgmt write denied",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# biomedical creates visit with multiple assets and initial complaint
|
||||
create_res = client.post(
|
||||
"/api/visits",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"department_id": icu.id,
|
||||
"visit_date": "2026-05-10",
|
||||
"observations": "Checked ICU beds 1-4; alarm issue noted on ventilator.",
|
||||
"asset_ids": [a.id for a in icu_assets],
|
||||
"complaint_ids": [complaints[0].id],
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
visit = create_res.json()
|
||||
visit_id = visit["id"]
|
||||
assert len(visit["assets"]) == 2
|
||||
assert [c["id"] for c in visit["complaints"]] == [complaints[0].id]
|
||||
|
||||
# management can GET /api/visits/{id} (200) but gets 403 on link-complaint and PATCH
|
||||
assert client.get(f"/api/visits/{visit_id}", headers=mgmt_headers).status_code == 200
|
||||
assert (
|
||||
client.post(
|
||||
f"/api/visits/{visit_id}/link-complaint",
|
||||
headers=mgmt_headers,
|
||||
json={"complaint_id": complaints[1].id},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/visits/{visit_id}",
|
||||
headers=mgmt_headers,
|
||||
json={"observations": "Should fail"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# biomedical links a second complaint (and linking duplicate is idempotent)
|
||||
link1 = client.post(
|
||||
f"/api/visits/{visit_id}/link-complaint",
|
||||
headers=bio_headers,
|
||||
json={"complaint_id": complaints[1].id},
|
||||
)
|
||||
assert link1.status_code == 200, link1.text
|
||||
assert {c["id"] for c in link1.json()["complaints"]} == {complaints[0].id, complaints[1].id}
|
||||
|
||||
link_dup = client.post(
|
||||
f"/api/visits/{visit_id}/link-complaint",
|
||||
headers=bio_headers,
|
||||
json={"complaint_id": complaints[1].id},
|
||||
)
|
||||
assert link_dup.status_code == 200
|
||||
assert len(link_dup.json()["complaints"]) == 2
|
||||
@@ -0,0 +1,153 @@
|
||||
import pytest
|
||||
|
||||
from app.models import Asset, AuditLog, Base, Department, User
|
||||
from app.routers.auth import MAX_LOGIN_ATTEMPTS, reset_login_rate_limiter
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_phase8_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("phase8_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||
assert res.status_code == 200, res.text
|
||||
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
|
||||
|
||||
def test_global_search_grouped_and_department_scoped(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
dept_user = db.query(User).filter(User.email == "dept@poona.demo").first()
|
||||
icu_dept = db.query(Department).filter(Department.id == dept_user.department_id).first()
|
||||
assert dept_user is not None and icu_dept is not None
|
||||
|
||||
icu_asset = db.query(Asset).filter(Asset.department_id == icu_dept.id).first()
|
||||
non_icu_asset = db.query(Asset).filter(Asset.department_id != icu_dept.id).first()
|
||||
assert icu_asset is not None and non_icu_asset is not None
|
||||
|
||||
# Broad search returns grouped assets & complaints capped at 8 each
|
||||
broad = client.get("/api/search?q=PHRC", headers=bio_headers)
|
||||
assert broad.status_code == 200, broad.text
|
||||
data = broad.json()
|
||||
assert isinstance(data["assets"], list) and 0 < len(data["assets"]) <= 8
|
||||
assert isinstance(data["complaints"], list) and len(data["complaints"]) <= 8
|
||||
assert {"id", "asset_code", "name", "serial_no", "department_name", "status"}.issubset(
|
||||
data["assets"][0].keys()
|
||||
)
|
||||
|
||||
# Complaint search by prefix
|
||||
cmp_search = client.get("/api/search?q=CMP", headers=bio_headers)
|
||||
assert cmp_search.status_code == 200
|
||||
assert len(cmp_search.json()["complaints"]) > 0
|
||||
assert {
|
||||
"id",
|
||||
"complaint_no",
|
||||
"asset_code",
|
||||
"asset_name",
|
||||
"department_name",
|
||||
"call_status",
|
||||
"priority",
|
||||
}.issubset(cmp_search.json()["complaints"][0].keys())
|
||||
|
||||
# Department user sees ICU asset, cannot see non-ICU asset
|
||||
icu_res = client.get(f"/api/search?q={icu_asset.asset_code}", headers=dept_headers)
|
||||
assert icu_res.status_code == 200
|
||||
assert any(a["asset_code"] == icu_asset.asset_code for a in icu_res.json()["assets"])
|
||||
|
||||
other_res = client.get(f"/api/search?q={non_icu_asset.asset_code}", headers=dept_headers)
|
||||
assert other_res.status_code == 200
|
||||
assert other_res.json()["assets"] == []
|
||||
assert other_res.json()["complaints"] == []
|
||||
|
||||
# Empty query rejected
|
||||
assert client.get("/api/search?q=", headers=bio_headers).status_code == 422
|
||||
|
||||
|
||||
def test_audit_logs_rbac_and_filters(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
for email in ("bio@poona.demo", "mgmt@poona.demo", "dept@poona.demo", "coord@poona.demo"):
|
||||
headers = _auth_headers(client, email)
|
||||
assert client.get("/api/audit-logs", headers=headers).status_code == 403
|
||||
|
||||
# Ensure there is at least one distinct AuditLog entry via API/DB
|
||||
admin_user = db.query(User).filter(User.email == "admin@poona.demo").first()
|
||||
assert admin_user is not None
|
||||
log_entry = AuditLog(
|
||||
entity_type="asset",
|
||||
entity_id=9999,
|
||||
action="phase8_audit_probe",
|
||||
changes_json='{"status": {"old": "in_service", "new": "under_repair"}}',
|
||||
by_user_id=admin_user.id,
|
||||
)
|
||||
db.add(log_entry)
|
||||
db.commit()
|
||||
|
||||
res = client.get("/api/audit-logs?entity_type=asset&action=phase8_audit_probe", headers=admin_headers)
|
||||
assert res.status_code == 200, res.text
|
||||
body = res.json()
|
||||
assert body["total"] >= 1
|
||||
assert len(body["items"]) >= 1
|
||||
first = body["items"][0]
|
||||
assert first["entity_type"] == "asset"
|
||||
assert first["action"] == "phase8_audit_probe"
|
||||
assert first["by_user_id"] == admin_user.id
|
||||
assert first["by_user_name"] == admin_user.name
|
||||
assert "under_repair" in first["changes_json"]
|
||||
|
||||
# Search filter `q`
|
||||
q_res = client.get("/api/audit-logs?q=phase8_audit_probe", headers=admin_headers)
|
||||
assert q_res.status_code == 200
|
||||
assert q_res.json()["total"] == 1
|
||||
|
||||
|
||||
def test_login_rate_limiter_429_and_reset(client):
|
||||
reset_login_rate_limiter()
|
||||
for i in range(MAX_LOGIN_ATTEMPTS):
|
||||
res = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "ratelimit@poona.demo", "password": "WrongPassword"},
|
||||
)
|
||||
assert res.status_code == 401, f"Attempt {i + 1} unexpected status {res.status_code}"
|
||||
|
||||
# Attempt 16 triggers 429 RATE_LIMITED
|
||||
blocked = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "ratelimit@poona.demo", "password": "WrongPassword"},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
assert blocked.json()["code"] == "RATE_LIMITED"
|
||||
|
||||
# Reset restores login capability
|
||||
reset_login_rate_limiter()
|
||||
ok = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "admin@poona.demo", "password": "Demo@123"},
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
|
||||
|
||||
def test_database_indexes_defined():
|
||||
expected_indexed_columns = {
|
||||
"assets": {"asset_code", "serial_no", "department_id", "category_id", "location_id", "status"},
|
||||
"complaints": {"complaint_no", "asset_id", "registered_at", "call_status", "assigned_to_id"},
|
||||
"contracts": {"asset_id", "start_date", "end_date"},
|
||||
"warranties": {"asset_id", "start_date", "end_date"},
|
||||
"insurance_policies": {"asset_id", "start_date", "end_date"},
|
||||
"calibration_records": {"asset_id", "plan_id", "due_date"},
|
||||
"pm_records": {"asset_id", "schedule_id", "planned_date"},
|
||||
"demo_equipment": {"department_id", "expected_return_date"},
|
||||
"department_visits": {"department_id", "visit_date"},
|
||||
"attachments": {"entity_type", "entity_id"},
|
||||
"notifications": {"created_at", "type"},
|
||||
"audit_logs": {"entity_type", "entity_id", "by_user_id", "at"},
|
||||
}
|
||||
for table_name, cols in expected_indexed_columns.items():
|
||||
table = Base.metadata.tables[table_name]
|
||||
indexed = {col.name for idx in table.indexes for col in idx.columns}
|
||||
missing = cols - indexed
|
||||
assert not missing, f"Missing indexes on {table_name}: {missing}"
|
||||
@@ -0,0 +1,426 @@
|
||||
from datetime import date
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import add_months
|
||||
from app.models import (
|
||||
Asset,
|
||||
CalibrationPlan,
|
||||
CalibrationRecord,
|
||||
Category,
|
||||
Contract,
|
||||
Department,
|
||||
Location,
|
||||
PMRecord,
|
||||
PMSchedule,
|
||||
Vendor,
|
||||
)
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_pm_cal_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("pm_cal_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 _create_test_asset(client, headers, db, code_suffix: str, req_cal: bool = False) -> int:
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
loc = db.query(Location).filter(Location.department_id == icu.id).first()
|
||||
cat = db.query(Category).first()
|
||||
res = client.post(
|
||||
"/api/assets",
|
||||
headers=headers,
|
||||
json={
|
||||
"asset_code": f"PHRC-PMCAL-{code_suffix}",
|
||||
"serial_no": f"SN-PMCAL-{code_suffix}",
|
||||
"name": f"PM Cal Test Unit {code_suffix}",
|
||||
"category_id": cat.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": loc.id,
|
||||
"status": "in_service",
|
||||
"criticality": "critical",
|
||||
"requires_calibration": req_cal,
|
||||
"insurance_applicable": False,
|
||||
},
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
return res.json()["id"]
|
||||
|
||||
|
||||
def test_add_months_clamping_and_db_note_n2(db):
|
||||
assert add_months(date(2026, 1, 31), 1) == date(2026, 2, 28)
|
||||
assert add_months(date(2024, 1, 31), 1) == date(2024, 2, 29)
|
||||
assert add_months(date(2026, 3, 31), 3) == date(2026, 6, 30)
|
||||
assert add_months(date(2026, 10, 15), 4) == date(2027, 2, 15)
|
||||
|
||||
# Note N2: seeded DB never persists 'upcoming', 'due', or 'overdue'
|
||||
bad_cal = (
|
||||
db.query(CalibrationRecord)
|
||||
.filter(CalibrationRecord.status.in_(["upcoming", "due", "overdue"]))
|
||||
.count()
|
||||
)
|
||||
bad_pm = (
|
||||
db.query(PMRecord)
|
||||
.filter(PMRecord.status.in_(["upcoming", "due", "overdue"]))
|
||||
.count()
|
||||
)
|
||||
assert bad_cal == 0
|
||||
assert bad_pm == 0
|
||||
|
||||
|
||||
def test_outsourced_pm_lifecycle_complete_and_reschedule(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
|
||||
provider = db.query(Vendor).filter(Vendor.vendor_type == "service_provider").first()
|
||||
contract = db.query(Contract).filter(Contract.is_superseded.is_(False)).first()
|
||||
asset_id = contract.asset_id
|
||||
|
||||
# Forbidden for department_user and management
|
||||
forbid_res = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"service_mode": "in_house",
|
||||
"frequency_months": 3,
|
||||
"responsible_team": "ICU Bio",
|
||||
"next_planned_date": "2026-06-10",
|
||||
},
|
||||
)
|
||||
assert forbid_res.status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=mgmt_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"service_mode": "in_house",
|
||||
"frequency_months": 3,
|
||||
"responsible_team": "Bio Team",
|
||||
"next_planned_date": "2026-06-10",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# Outsourced PM schedule without provider_id/contract_id auto-fills from active AMC/CMC
|
||||
auto_out = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"service_mode": "outsourced",
|
||||
"frequency_months": 3,
|
||||
"next_planned_date": "2026-06-10",
|
||||
},
|
||||
)
|
||||
assert auto_out.status_code == 201, auto_out.text
|
||||
assert auto_out.json()["contract_id"] == contract.id
|
||||
assert auto_out.json()["provider_id"] == contract.provider_id
|
||||
|
||||
# Create outsourced PM schedule with provider + contract
|
||||
sched_res = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"service_mode": "outsourced",
|
||||
"frequency_months": 3,
|
||||
"provider_id": contract.provider_id or provider.id,
|
||||
"contract_id": contract.id,
|
||||
"next_planned_date": "2026-06-10",
|
||||
},
|
||||
)
|
||||
assert sched_res.status_code == 201, sched_res.text
|
||||
sched = sched_res.json()
|
||||
assert sched["service_mode"] == "outsourced"
|
||||
assert sched["contract_id"] == contract.id
|
||||
assert sched["contract_summary"] is not None
|
||||
|
||||
# Initial PMRecord was created with planned_date=2026-06-10 and DB status=None
|
||||
recs_res = client.get(f"/api/pm/records?schedule_id={sched['id']}", headers=bio_headers)
|
||||
assert recs_res.status_code == 200
|
||||
items = recs_res.json()["items"]
|
||||
assert len(items) == 1
|
||||
first_rec_id = items[0]["id"]
|
||||
assert items[0]["planned_date"] == "2026-06-10"
|
||||
db.expire_all()
|
||||
assert db.query(PMRecord).filter(PMRecord.id == first_rec_id).first().status is None
|
||||
|
||||
# Complete the initial PMRecord on 2026-06-12 -> next planned 2026-09-12
|
||||
comp_res = client.post(
|
||||
f"/api/pm/records/{first_rec_id}/complete",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"completed_date": "2026-06-12",
|
||||
"service_details": "Replaced flow sensor filter and verified pressure calibration.",
|
||||
"remarks": "Vendor engineer visit completed.",
|
||||
},
|
||||
)
|
||||
assert comp_res.status_code == 200, comp_res.text
|
||||
comp_data = comp_res.json()
|
||||
assert comp_data["completed_record"]["status"] == "completed"
|
||||
assert comp_data["completed_record"]["completed_date"] == "2026-06-12"
|
||||
assert comp_data["next_record"]["planned_date"] == "2026-09-12"
|
||||
|
||||
# Re-completing same record -> 400
|
||||
recomp = client.post(
|
||||
f"/api/pm/records/{first_rec_id}/complete",
|
||||
headers=bio_headers,
|
||||
json={"completed_date": "2026-06-13", "service_details": "Duplicate"},
|
||||
)
|
||||
assert recomp.status_code == 400
|
||||
|
||||
# Reschedule the generated next record from 2026-09-12 to 2026-09-25
|
||||
second_rec_id = comp_data["next_record"]["id"]
|
||||
resched_res = client.post(
|
||||
f"/api/pm/records/{second_rec_id}/reschedule",
|
||||
headers=bio_headers,
|
||||
json={"rescheduled_to": "2026-09-25", "remarks": "OT occupied on 12 Sep."},
|
||||
)
|
||||
assert resched_res.status_code == 200, resched_res.text
|
||||
resched_data = resched_res.json()
|
||||
assert resched_data["rescheduled_record"]["status"] == "rescheduled"
|
||||
assert resched_data["rescheduled_record"]["rescheduled_to"] == "2026-09-25"
|
||||
assert resched_data["next_record"]["planned_date"] == "2026-09-25"
|
||||
|
||||
# Verify schedule next_planned_date updated and deactivate schedule works
|
||||
del_res = client.delete(f"/api/pm/schedules/{sched['id']}", headers=bio_headers)
|
||||
assert del_res.status_code == 200
|
||||
assert del_res.json()["is_active"] is False
|
||||
|
||||
|
||||
def test_calibration_plan_approval_permissions_and_completion(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
a1 = _create_test_asset(client, bio_headers, db, "001", req_cal=False)
|
||||
a2 = _create_test_asset(client, bio_headers, db, "002", req_cal=False)
|
||||
a3 = _create_test_asset(client, bio_headers, db, "003", req_cal=True)
|
||||
agency = db.query(Vendor).filter(Vendor.vendor_type == "calibration_agency").first()
|
||||
|
||||
# Biomedical cannot create with approve=True
|
||||
forbid_create_app = client.post(
|
||||
f"/api/calibration/plans/from-asset/{a1}",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"frequency_months": 6,
|
||||
"agency_id": agency.id,
|
||||
"next_due_date": "2026-08-01",
|
||||
"approve": True,
|
||||
},
|
||||
)
|
||||
assert forbid_create_app.status_code == 403
|
||||
assert forbid_create_app.json()["code"] == "FORBIDDEN_CALIBRATION_APPROVAL"
|
||||
|
||||
# Biomedical creates unapproved plan from asset -> sets requires_calibration=True
|
||||
c1 = client.post(
|
||||
f"/api/calibration/plans/from-asset/{a1}",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"frequency_months": 6,
|
||||
"agency_id": agency.id,
|
||||
"next_due_date": "2026-08-01",
|
||||
"approve": False,
|
||||
},
|
||||
)
|
||||
assert c1.status_code == 201, c1.text
|
||||
plan1 = c1.json()
|
||||
assert plan1["calibrations_per_year"] == 2
|
||||
assert plan1["approved_by_id"] is None
|
||||
db.expire_all()
|
||||
assert db.query(Asset).filter(Asset.id == a1).first().requires_calibration is True
|
||||
|
||||
# Duplicate from-asset -> 409 DUPLICATE_CALIBRATION_PLAN
|
||||
dup = client.post(
|
||||
f"/api/calibration/plans/from-asset/{a1}",
|
||||
headers=bio_headers,
|
||||
json={"frequency_months": 6, "next_due_date": "2026-08-01"},
|
||||
)
|
||||
assert dup.status_code == 409
|
||||
assert dup.json()["code"] == "DUPLICATE_CALIBRATION_PLAN"
|
||||
|
||||
# Bulk add with a1 (already has plan) + a2 + a3
|
||||
bulk_res = client.post(
|
||||
"/api/calibration/plans/bulk-from-assets",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_ids": [a1, a2, a3],
|
||||
"frequency_months": 12,
|
||||
"agency_id": agency.id,
|
||||
"next_due_date": "2026-10-15",
|
||||
"approve": False,
|
||||
},
|
||||
)
|
||||
assert bulk_res.status_code == 200, bulk_res.text
|
||||
bulk_json = bulk_res.json()
|
||||
assert [p["asset_id"] for p in bulk_json["created"]] == [a2, a3]
|
||||
assert bulk_json["skipped_asset_ids"] == [a1]
|
||||
|
||||
# Biomedical gets 403 trying to modify frequency or approve; management succeeds (200)
|
||||
bio_freq = client.put(
|
||||
f"/api/calibration/plans/{plan1['id']}",
|
||||
headers=bio_headers,
|
||||
json={"frequency_months": 12},
|
||||
)
|
||||
assert bio_freq.status_code == 403
|
||||
assert bio_freq.json()["code"] == "FORBIDDEN_CALIBRATION_APPROVAL"
|
||||
|
||||
bio_app = client.post(f"/api/calibration/plans/{plan1['id']}/approve", headers=bio_headers)
|
||||
assert bio_app.status_code == 403
|
||||
|
||||
assert client.post(f"/api/calibration/plans/{plan1['id']}/approve", headers=dept_headers).status_code == 403
|
||||
|
||||
mgmt_freq = client.put(
|
||||
f"/api/calibration/plans/{plan1['id']}",
|
||||
headers=mgmt_headers,
|
||||
json={"frequency_months": 4},
|
||||
)
|
||||
assert mgmt_freq.status_code == 200
|
||||
assert mgmt_freq.json()["frequency_months"] == 4
|
||||
assert mgmt_freq.json()["calibrations_per_year"] == 3
|
||||
|
||||
mgmt_app = client.post(
|
||||
f"/api/calibration/plans/{plan1['id']}/approve",
|
||||
headers=mgmt_headers,
|
||||
json={"frequency_months": 6},
|
||||
)
|
||||
assert mgmt_app.status_code == 200, mgmt_app.text
|
||||
assert mgmt_app.json()["frequency_months"] == 6
|
||||
assert mgmt_app.json()["approved_by_name"] is not None
|
||||
assert mgmt_app.json()["approved_on"] is not None
|
||||
|
||||
# Complete calibration record -> creates next record at completed_date + frequency_months and preserves history
|
||||
cal_recs = client.get(f"/api/calibration/records?asset_id={a1}", headers=bio_headers).json()["items"]
|
||||
assert len(cal_recs) == 1
|
||||
rec1_id = cal_recs[0]["id"]
|
||||
|
||||
comp = client.post(
|
||||
f"/api/calibration/records/{rec1_id}/complete",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"completed_date": "2026-08-05",
|
||||
"certificate_no": "NABL-2026-9901",
|
||||
"agency_id": agency.id,
|
||||
"remarks": "All channels within +/-1% tolerance.",
|
||||
},
|
||||
)
|
||||
assert comp.status_code == 200, comp.text
|
||||
comp_json = comp.json()
|
||||
assert comp_json["completed_record"]["status"] == "completed"
|
||||
assert comp_json["completed_record"]["certificate_no"] == "NABL-2026-9901"
|
||||
assert comp_json["next_record"]["due_date"] == "2027-02-05"
|
||||
|
||||
# Both historical and next records exist for asset
|
||||
history = client.get(f"/api/calibration/records?asset_id={a1}", headers=bio_headers).json()
|
||||
assert history["total"] == 2
|
||||
assert history["summary"]["completed"] == 1
|
||||
|
||||
|
||||
def test_demo_clock_transitions_statuses_dynamically_on_read(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
asset_id = _create_test_asset(client, bio_headers, db, "CLK", req_cal=True)
|
||||
agency = db.query(Vendor).filter(Vendor.vendor_type == "calibration_agency").first()
|
||||
|
||||
# Calibration due 2028-06-20; PM planned 2028-06-20 (far future, no interference)
|
||||
cal_plan = client.post(
|
||||
f"/api/calibration/plans/from-asset/{asset_id}",
|
||||
headers=admin_headers,
|
||||
json={
|
||||
"frequency_months": 12,
|
||||
"agency_id": agency.id,
|
||||
"next_due_date": "2028-06-20",
|
||||
"approve": True,
|
||||
},
|
||||
)
|
||||
assert cal_plan.status_code == 201
|
||||
|
||||
pm_sched = client.post(
|
||||
"/api/pm/schedules",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"service_mode": "in_house",
|
||||
"frequency_months": 6,
|
||||
"responsible_team": "Bio Team A",
|
||||
"next_planned_date": "2028-06-20",
|
||||
},
|
||||
)
|
||||
assert pm_sched.status_code == 201
|
||||
|
||||
try:
|
||||
# 1) 2028-05-01 -> 50 days before due -> both 'upcoming' (ok)
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": "2028-05-01"},
|
||||
)
|
||||
cal1 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
pm1 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
ov1 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json()
|
||||
assert cal1["status"] == "upcoming" and cal1["severity"] == "ok"
|
||||
assert pm1["status"] == "upcoming" and pm1["severity"] == "ok"
|
||||
assert ov1["calibration_records"][0]["status"] == "upcoming"
|
||||
assert ov1["pm_records"][0]["status"] == "upcoming"
|
||||
|
||||
# 2) 2028-06-10 -> 10 days before due (<= 15 lead, > 7 red) -> both 'due' (yellow)
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": "2028-06-10"},
|
||||
)
|
||||
cal2 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
pm2 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
ov2 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json()
|
||||
assert cal2["status"] == "due" and cal2["severity"] == "yellow"
|
||||
assert pm2["status"] == "due" and pm2["severity"] == "yellow"
|
||||
assert ov2["calibration_records"][0]["status"] == "due"
|
||||
assert ov2["pm_records"][0]["status"] == "due"
|
||||
|
||||
# 3) 2028-06-15 -> 5 days before due (<= 7 red) -> 'due' (red)
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": "2028-06-15"},
|
||||
)
|
||||
cal3 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
pm3 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
assert cal3["status"] == "due" and cal3["severity"] == "red"
|
||||
assert pm3["status"] == "due" and pm3["severity"] == "red"
|
||||
|
||||
# 4) 2028-06-25 -> 5 days past due -> 'overdue' (red)
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": "2028-06-25"},
|
||||
)
|
||||
cal4 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
pm4 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
||||
ov4 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json()
|
||||
assert cal4["status"] == "overdue" and cal4["severity"] == "red"
|
||||
assert pm4["status"] == "overdue" and pm4["severity"] == "red"
|
||||
assert ov4["calibration_records"][0]["status"] == "overdue"
|
||||
assert ov4["pm_records"][0]["status"] == "overdue"
|
||||
|
||||
# Confirm DB status columns stayed NULL throughout!
|
||||
db.expire_all()
|
||||
assert db.query(CalibrationRecord).filter(CalibrationRecord.asset_id == asset_id).first().status is None
|
||||
assert db.query(PMRecord).filter(PMRecord.asset_id == asset_id).first().status is None
|
||||
finally:
|
||||
client.post(
|
||||
"/api/settings/demo-date",
|
||||
headers=admin_headers,
|
||||
json={"demo_as_of_date": None},
|
||||
)
|
||||
@@ -0,0 +1,275 @@
|
||||
import csv
|
||||
from datetime import datetime, timezone
|
||||
from io import BytesIO, StringIO
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import KOLKATA
|
||||
from app.models import Asset, Category, Complaint, Department, Location, User
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
ALL_REPORT_KEYS = [
|
||||
"monthly-maintenance",
|
||||
"monthly-department",
|
||||
"daily-visit",
|
||||
"breakdown-complaints",
|
||||
"pm-compliance",
|
||||
"calibration-due",
|
||||
"contracts-warranty",
|
||||
"demo-equipment",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_phase7_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("phase7_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||
assert res.status_code == 200, res.text
|
||||
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
|
||||
|
||||
def test_all_eight_reports_accessible_for_management_and_admin(client):
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
for headers in (mgmt_headers, admin_headers):
|
||||
for key in ALL_REPORT_KEYS:
|
||||
res = client.get(f"/api/reports/{key}", headers=headers)
|
||||
assert res.status_code == 200, f"{key} failed: {res.text}"
|
||||
body = res.json()
|
||||
assert body["report_key"] == key
|
||||
assert body["title"]
|
||||
assert isinstance(body["filters_applied"], dict)
|
||||
assert isinstance(body["summary"], dict)
|
||||
assert isinstance(body["columns"], list) and len(body["columns"]) > 0
|
||||
assert isinstance(body["rows"], list)
|
||||
|
||||
missing = client.get("/api/reports/non-existent-report", headers=admin_headers)
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
def test_daily_visit_rbac_and_department_user_scoping(client, db):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
# daily-visit is forbidden for department_user and coordinator (JSON + export)
|
||||
for headers in (dept_headers, coord_headers):
|
||||
assert client.get("/api/reports/daily-visit", headers=headers).status_code == 403
|
||||
assert client.get("/api/reports/daily-visit/export?format=xlsx", headers=headers).status_code == 403
|
||||
|
||||
# Allowed for biomedical engineer
|
||||
assert client.get("/api/reports/daily-visit", headers=bio_headers).status_code == 200
|
||||
|
||||
# Department user attempting to pass another department_id is still scoped to own department
|
||||
dept_user = db.query(User).filter(User.email == "dept@poona.demo").first()
|
||||
other_dept = db.query(Department).filter(Department.id != dept_user.department_id).first()
|
||||
assert dept_user is not None and dept_user.department_id is not None
|
||||
assert other_dept is not None
|
||||
|
||||
for key in [k for k in ALL_REPORT_KEYS if k != "daily-visit"]:
|
||||
res = client.get(
|
||||
f"/api/reports/{key}?department_id={other_dept.id}",
|
||||
headers=dept_headers,
|
||||
)
|
||||
assert res.status_code == 200, f"{key} failed for dept user: {res.text}"
|
||||
body = res.json()
|
||||
if "department_id" in body["filters_applied"]:
|
||||
assert body["filters_applied"]["department_id"] == dept_user.department_id
|
||||
|
||||
maint = client.get(
|
||||
f"/api/reports/monthly-maintenance?department_id={other_dept.id}",
|
||||
headers=dept_headers,
|
||||
).json()
|
||||
assert len(maint["rows"]) == 1
|
||||
assert maint["rows"][0]["department_id"] == dept_user.department_id
|
||||
|
||||
|
||||
def test_monthly_maintenance_three_complaint_reconciliation(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
admin_user = db.query(User).filter(User.email == "admin@poona.demo").first()
|
||||
category = db.query(Category).first()
|
||||
location = db.query(Location).first()
|
||||
assert admin_user is not None and category is not None and location is not None
|
||||
|
||||
# Create isolated department with 2 non-condemned assets so calculation is deterministic
|
||||
dept = Department(name="Reconciliation Test Unit", code="REC-TEST-01", is_active=True)
|
||||
db.add(dept)
|
||||
db.flush()
|
||||
|
||||
asset1 = Asset(
|
||||
asset_code="REC-AST-001",
|
||||
serial_no="REC-SN-001",
|
||||
name="Reconciliation Monitor 1",
|
||||
category_id=category.id,
|
||||
department_id=dept.id,
|
||||
location_id=location.id,
|
||||
status="in_service",
|
||||
criticality="critical",
|
||||
)
|
||||
asset2 = Asset(
|
||||
asset_code="REC-AST-002",
|
||||
serial_no="REC-SN-002",
|
||||
name="Reconciliation Monitor 2",
|
||||
category_id=category.id,
|
||||
department_id=dept.id,
|
||||
location_id=location.id,
|
||||
status="in_service",
|
||||
criticality="non_critical",
|
||||
)
|
||||
db.add_all([asset1, asset2])
|
||||
db.flush()
|
||||
|
||||
# 3 fixed complaints for March 2027 (31 days * 24h * 60m = 44640 mins/asset -> 89280 total):
|
||||
# 1) Crosses month boundary: Feb 28 22:00 IST -> Mar 01 04:00 IST => 240 mins in March, day Mar 01
|
||||
# 2) Mid-month: Mar 10 10:00 IST -> Mar 10 13:30 IST => 210 mins, day Mar 10
|
||||
# 3) Distinct day: Mar 20 09:00 IST -> Mar 20 10:15 IST => 75 mins, day Mar 20
|
||||
# Expected total downtime = 525 mins, downtime days = 3, uptime = 88755 mins
|
||||
complaints = [
|
||||
Complaint(
|
||||
complaint_no="REC-CMP-001",
|
||||
asset_id=asset1.id,
|
||||
description="Month boundary downtime test",
|
||||
priority="critical",
|
||||
registered_at=KOLKATA.localize(datetime(2027, 2, 28, 22, 0)).astimezone(timezone.utc),
|
||||
restored_at=KOLKATA.localize(datetime(2027, 3, 1, 4, 0)).astimezone(timezone.utc),
|
||||
registered_by_id=admin_user.id,
|
||||
received_by_id=admin_user.id,
|
||||
call_status="closed",
|
||||
),
|
||||
Complaint(
|
||||
complaint_no="REC-CMP-002",
|
||||
asset_id=asset1.id,
|
||||
description="Mid-month downtime test",
|
||||
priority="non_critical",
|
||||
registered_at=KOLKATA.localize(datetime(2027, 3, 10, 10, 0)).astimezone(timezone.utc),
|
||||
restored_at=KOLKATA.localize(datetime(2027, 3, 10, 13, 30)).astimezone(timezone.utc),
|
||||
registered_by_id=admin_user.id,
|
||||
received_by_id=admin_user.id,
|
||||
call_status="closed",
|
||||
),
|
||||
Complaint(
|
||||
complaint_no="REC-CMP-003",
|
||||
asset_id=asset2.id,
|
||||
description="Third distinct day downtime test",
|
||||
priority="non_critical",
|
||||
registered_at=KOLKATA.localize(datetime(2027, 3, 20, 9, 0)).astimezone(timezone.utc),
|
||||
restored_at=KOLKATA.localize(datetime(2027, 3, 20, 10, 15)).astimezone(timezone.utc),
|
||||
registered_by_id=admin_user.id,
|
||||
received_by_id=admin_user.id,
|
||||
call_status="closed",
|
||||
),
|
||||
]
|
||||
db.add_all(complaints)
|
||||
db.commit()
|
||||
|
||||
res = client.get(
|
||||
f"/api/reports/monthly-maintenance?month=2027-03&department_id={dept.id}",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
payload = res.json()
|
||||
|
||||
summary = payload["summary"]
|
||||
assert summary["total_assets"] == 2
|
||||
assert summary["total_complaints"] == 3
|
||||
assert summary["total_downtime_minutes"] == 525
|
||||
assert summary["downtime_days_count"] == 3
|
||||
assert summary["total_scheduled_minutes"] == 89280
|
||||
assert summary["total_uptime_minutes"] == 88755
|
||||
assert summary["downtime_pct"] == round(525 / 89280 * 100, 2)
|
||||
|
||||
assert len(payload["rows"]) == 1
|
||||
row = payload["rows"][0]
|
||||
assert row["department_name"] == "Reconciliation Test Unit"
|
||||
assert row["asset_count"] == 2
|
||||
assert row["complaint_count"] == 3
|
||||
assert row["total_downtime_minutes"] == 525
|
||||
assert row["downtime_days_count"] == 3
|
||||
assert row["scheduled_minutes"] == 89280
|
||||
assert row["total_uptime_minutes"] == 88755
|
||||
|
||||
|
||||
def test_report_exports_xlsx_and_csv(client):
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
|
||||
# Excel export
|
||||
xlsx_res = client.get(
|
||||
"/api/reports/monthly-maintenance/export?format=xlsx&month=2027-03",
|
||||
headers=mgmt_headers,
|
||||
)
|
||||
assert xlsx_res.status_code == 200
|
||||
assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"]
|
||||
assert 'filename="monthly-maintenance.xlsx"' in xlsx_res.headers["content-disposition"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(xlsx_res.content))
|
||||
ws = wb.active
|
||||
assert "Poona Hospital" in str(ws["A1"].value)
|
||||
assert "Generated:" in str(ws["A2"].value)
|
||||
assert "Filters:" in str(ws["A2"].value)
|
||||
assert "Total Downtime Minutes: 525" in str(ws["A3"].value)
|
||||
assert ws.freeze_panes == "A6"
|
||||
assert ws.cell(row=5, column=1).value == "Department"
|
||||
assert "1E3A8A" in str(ws.cell(row=5, column=1).fill.start_color.rgb)
|
||||
assert ws.max_row >= 6
|
||||
|
||||
# CSV export
|
||||
csv_res = client.get(
|
||||
"/api/reports/breakdown-complaints/export?format=csv",
|
||||
headers=mgmt_headers,
|
||||
)
|
||||
assert csv_res.status_code == 200
|
||||
assert "text/csv" in csv_res.headers["content-type"]
|
||||
assert 'filename="breakdown-complaints.csv"' in csv_res.headers["content-disposition"]
|
||||
assert csv_res.content.startswith(b"\xef\xbb\xbf")
|
||||
|
||||
decoded = csv_res.content.decode("utf-8-sig")
|
||||
parsed = list(csv.reader(StringIO(decoded)))
|
||||
assert len(parsed) >= 5
|
||||
assert "Poona Hospital" in parsed[0][0]
|
||||
assert parsed[4][0] == "Complaint No"
|
||||
|
||||
# Unsupported export format rejected
|
||||
bad_fmt = client.get(
|
||||
"/api/reports/monthly-maintenance/export?format=pdf",
|
||||
headers=mgmt_headers,
|
||||
)
|
||||
assert bad_fmt.status_code == 422
|
||||
|
||||
|
||||
def test_all_eight_reports_export_xlsx_and_csv(client):
|
||||
"""Verify that all 8 reports export cleanly as both XLSX and CSV without title/slash errors."""
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
for key in ALL_REPORT_KEYS:
|
||||
# Test XLSX export
|
||||
xlsx_res = client.get(
|
||||
f"/api/reports/{key}/export?format=xlsx",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert xlsx_res.status_code == 200, f"XLSX export failed for {key}: {xlsx_res.text}"
|
||||
assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"]
|
||||
assert f'filename="{key}.xlsx"' in xlsx_res.headers["content-disposition"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(xlsx_res.content))
|
||||
ws = wb.active
|
||||
assert ws is not None
|
||||
assert "/" not in ws.title and "\\" not in ws.title
|
||||
assert len(ws.title) <= 31
|
||||
|
||||
# Test CSV export
|
||||
csv_res = client.get(
|
||||
f"/api/reports/{key}/export?format=csv",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert csv_res.status_code == 200, f"CSV export failed for {key}: {csv_res.text}"
|
||||
assert "text/csv" in csv_res.headers["content-type"]
|
||||
assert f'filename="{key}.csv"' in csv_res.headers["content-disposition"]
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
from io import BytesIO
|
||||
from datetime import date
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.models import Asset, CalibrationPlan, Contract, Department, InsurancePolicy, Vendor
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task1_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task1_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str = "admin@poona.demo") -> 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 _make_xlsx_bytes(sheet_name: str, headers: list[str], rows: list[list]) -> bytes:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = sheet_name
|
||||
ws.append(headers)
|
||||
for r in rows:
|
||||
ws.append(r)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_contracts_api_duplicate_409(client, db):
|
||||
headers = _auth_headers(client)
|
||||
asset = db.query(Asset).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset and vendor
|
||||
|
||||
payload = {
|
||||
"asset_id": asset.id,
|
||||
"contract_type": "AMC",
|
||||
"provider_id": vendor.id,
|
||||
"start_date": "2026-01-01",
|
||||
"end_date": "2026-12-31",
|
||||
"coverage_period_text": "2026 Annual AMC",
|
||||
}
|
||||
# First creation should succeed
|
||||
res1 = client.post("/api/contracts", json=payload, headers=headers)
|
||||
assert res1.status_code == 201
|
||||
contract_id = res1.json()["id"]
|
||||
|
||||
# Second creation with identical asset, type, start_date, end_date must return 409
|
||||
res2 = client.post("/api/contracts", json=payload, headers=headers)
|
||||
assert res2.status_code == 409
|
||||
assert res2.json()["detail"] == "A contract with the same asset, type and dates already exists."
|
||||
|
||||
# Renewal must still work
|
||||
renew_payload = {
|
||||
"start_date": "2027-01-01",
|
||||
"end_date": "2027-12-31",
|
||||
"contract_type": "AMC",
|
||||
"coverage_period_text": "2027 Annual Renewal",
|
||||
}
|
||||
res_renew = client.post(f"/api/contracts/{contract_id}/renew", json=renew_payload, headers=headers)
|
||||
assert res_renew.status_code == 200
|
||||
assert res_renew.json()["new_contract"]["start_date"] == "2027-01-01"
|
||||
|
||||
|
||||
def test_insurance_api_duplicate_409(client, db):
|
||||
headers = _auth_headers(client)
|
||||
asset = db.query(Asset).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset and vendor
|
||||
|
||||
policy_no = "POL-DUP-TEST-999"
|
||||
payload = {
|
||||
"asset_id": asset.id,
|
||||
"insurer_id": vendor.id,
|
||||
"policy_no": f" {policy_no} ",
|
||||
"start_date": "2026-04-01",
|
||||
"end_date": "2027-03-31",
|
||||
"coverage_amount": 500000.0,
|
||||
}
|
||||
# First creation succeeds
|
||||
res1 = client.post("/api/insurance", json=payload, headers=headers)
|
||||
assert res1.status_code == 201
|
||||
|
||||
# Exact duplicate (case-insensitive and trimmed) must return 409
|
||||
dup_payload = {
|
||||
"asset_id": asset.id,
|
||||
"insurer_id": vendor.id,
|
||||
"policy_no": f"pol-dup-test-999 ",
|
||||
"start_date": "2026-04-01",
|
||||
"end_date": "2027-03-31",
|
||||
}
|
||||
res2 = client.post("/api/insurance", json=dup_payload, headers=headers)
|
||||
assert res2.status_code == 409
|
||||
assert res2.json()["detail"] == "Policy number already exists."
|
||||
|
||||
|
||||
def test_contracts_bulk_import_in_file_and_db_duplicates(client, db):
|
||||
headers = _auth_headers(client)
|
||||
asset = db.query(Asset).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset and vendor
|
||||
|
||||
xlsx_headers = ["asset_code", "provider_name", "contract_type", "start_date", "end_date", "cost", "coverage_details", "remarks"]
|
||||
rows = [
|
||||
[asset.asset_code, vendor.name, "AMC", "2028-01-01", "2028-12-31", 10000, "Coverage", "Remark 1"],
|
||||
[asset.asset_code, vendor.name, "AMC", "2028-01-01", "2028-12-31", 10000, "Coverage", "Remark 2"],
|
||||
]
|
||||
file_bytes = _make_xlsx_bytes("Contracts", xlsx_headers, rows)
|
||||
|
||||
# Dry run should flag row 3 as duplicate of row 2
|
||||
res_dry = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=true",
|
||||
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_dry.status_code == 200
|
||||
dry_data = res_dry.json()
|
||||
assert dry_data["valid_count"] == 1
|
||||
assert dry_data["error_count"] == 1
|
||||
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
|
||||
|
||||
# Import with skip_invalid=true creates exactly 1 record
|
||||
res_imp1 = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp1.status_code == 200
|
||||
assert res_imp1.json()["created_count"] == 1
|
||||
|
||||
# Second import of the same file creates 0 records and reports DB duplicates
|
||||
res_imp2 = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp2.status_code == 200
|
||||
data2 = res_imp2.json()
|
||||
assert data2["created_count"] == 0
|
||||
assert data2["error_count"] == 2
|
||||
messages = [e["message"] for e in data2["errors"]]
|
||||
assert any("Already exists in the system." in m for m in messages)
|
||||
assert any("Duplicate of row 2 in this file." in m for m in messages)
|
||||
|
||||
|
||||
def test_insurance_bulk_import_in_file_and_db_duplicates(client, db):
|
||||
headers = _auth_headers(client)
|
||||
asset = db.query(Asset).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset and vendor
|
||||
|
||||
xlsx_headers = ["asset_code", "insurer_name", "policy_number", "start_date", "end_date", "insured_value", "premium", "remarks"]
|
||||
rows = [
|
||||
[asset.asset_code, vendor.name, "POL-BULK-101", "2028-01-01", "2028-12-31", 200000, 5000, "Policy row 2"],
|
||||
[asset.asset_code, vendor.name, " pol-bulk-101 ", "2028-01-01", "2028-12-31", 200000, 5000, "Policy row 3"],
|
||||
]
|
||||
file_bytes = _make_xlsx_bytes("Insurance Policies", xlsx_headers, rows)
|
||||
|
||||
# Dry run should flag row 3 as duplicate of row 2
|
||||
res_dry = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=true",
|
||||
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_dry.status_code == 200
|
||||
dry_data = res_dry.json()
|
||||
assert dry_data["valid_count"] == 1
|
||||
assert dry_data["error_count"] == 1
|
||||
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
|
||||
|
||||
# Import with skip_invalid=true creates 1 record
|
||||
res_imp1 = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp1.status_code == 200
|
||||
assert res_imp1.json()["created_count"] == 1
|
||||
|
||||
# Second import creates 0 records
|
||||
res_imp2 = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp2.status_code == 200
|
||||
data2 = res_imp2.json()
|
||||
assert data2["created_count"] == 0
|
||||
assert data2["error_count"] == 2
|
||||
messages = [e["message"] for e in data2["errors"]]
|
||||
assert any("Already exists in the system." in m for m in messages)
|
||||
assert any("Duplicate of row 2 in this file." in m for m in messages)
|
||||
|
||||
|
||||
def test_calibration_bulk_import_in_file_and_existing_plan(client, db):
|
||||
headers = _auth_headers(client)
|
||||
from app.models import CalibrationPlan
|
||||
planned_ids = {p.asset_id for p in db.query(CalibrationPlan.asset_id).all()}
|
||||
asset = db.query(Asset).filter(~Asset.id.in_(planned_ids)).first()
|
||||
if not asset:
|
||||
dept = db.query(Department).first()
|
||||
asset = Asset(
|
||||
asset_code="PHRC-TEST-CAL-99",
|
||||
name="Test Cal Asset",
|
||||
department_id=dept.id,
|
||||
status="in_service",
|
||||
requires_calibration=True,
|
||||
)
|
||||
db.add(asset)
|
||||
db.commit()
|
||||
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
|
||||
xlsx_headers = ["asset_code", "frequency_months", "agency_name", "next_due_date", "scope", "standards", "remarks"]
|
||||
rows = [
|
||||
[asset.asset_code, 12, vendor.name if vendor else "", "2028-06-01", "Accredited scope", "ISO 17025", "Cal row 2"],
|
||||
[asset.asset_code, 6, vendor.name if vendor else "", "2028-06-01", "Accredited scope", "ISO 17025", "Cal row 3"],
|
||||
]
|
||||
file_bytes = _make_xlsx_bytes("Calibration Plans", xlsx_headers, rows)
|
||||
|
||||
# Dry run flags row 3 as duplicate of row 2
|
||||
res_dry = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=true",
|
||||
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_dry.status_code == 200
|
||||
dry_data = res_dry.json()
|
||||
assert dry_data["valid_count"] == 1
|
||||
assert dry_data["error_count"] == 1
|
||||
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
|
||||
|
||||
# Import with skip_invalid=true creates 1 record
|
||||
res_imp1 = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp1.status_code == 200
|
||||
assert res_imp1.json()["created_count"] == 1
|
||||
|
||||
# Second import creates 0 records and reports "Asset already has a calibration plan."
|
||||
res_imp2 = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=false&skip_invalid=true",
|
||||
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_imp2.status_code == 200
|
||||
data2 = res_imp2.json()
|
||||
assert data2["created_count"] == 0
|
||||
assert data2["error_count"] == 2
|
||||
messages = [e["message"] for e in data2["errors"]]
|
||||
assert any("Asset already has a calibration plan." in m for m in messages)
|
||||
assert any("Duplicate of row 2 in this file." in m for m in messages)
|
||||
@@ -0,0 +1,89 @@
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task2_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task2_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str = "admin@poona.demo") -> 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']}"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"template_url,import_url,file_field,filename,expected_sheet1",
|
||||
[
|
||||
(
|
||||
"/api/assets/import-template",
|
||||
"/api/assets/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"asset_template.xlsx",
|
||||
"Assets",
|
||||
),
|
||||
(
|
||||
"/api/contracts/import-template",
|
||||
"/api/contracts/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"contracts_template.xlsx",
|
||||
"Contracts",
|
||||
),
|
||||
(
|
||||
"/api/calibration/import-template",
|
||||
"/api/calibration/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"calibration_template.xlsx",
|
||||
"Calibration Plans",
|
||||
),
|
||||
(
|
||||
"/api/insurance/import-template",
|
||||
"/api/insurance/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"insurance_template.xlsx",
|
||||
"Insurance Policies",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_download_template_and_upload_unchanged_dry_run_zero_rows(
|
||||
client, template_url, import_url, file_field, filename, expected_sheet1
|
||||
):
|
||||
headers = _auth_headers(client)
|
||||
|
||||
# 1. Download template
|
||||
dl_res = client.get(template_url, headers=headers)
|
||||
assert dl_res.status_code == 200
|
||||
content = dl_res.content
|
||||
|
||||
# 2. Verify sheet structure
|
||||
wb = openpyxl.load_workbook(BytesIO(content))
|
||||
assert wb.sheetnames == [expected_sheet1, "Example", "Master Reference"]
|
||||
|
||||
ws1 = wb[expected_sheet1]
|
||||
# First sheet has only header row (max_row == 1)
|
||||
assert ws1.max_row == 1
|
||||
|
||||
ws2 = wb["Example"]
|
||||
# Second sheet has disclaimer on row 1
|
||||
assert ws2.cell(row=1, column=1).value == "Example only - this sheet is ignored on import"
|
||||
# Second sheet has sample row on row 2
|
||||
assert ws2.cell(row=2, column=1).value is not None
|
||||
|
||||
# 3. Upload unchanged template with dry_run=true: must return total_rows == 0
|
||||
up_res = client.post(
|
||||
import_url,
|
||||
headers=headers,
|
||||
files={file_field: (filename, content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert up_res.status_code == 200, up_res.text
|
||||
data = up_res.json()
|
||||
assert data["total_rows"] == 0
|
||||
assert data["valid_count"] == 0
|
||||
assert data["error_count"] == 0
|
||||
assert data["created_count"] == 0
|
||||
@@ -0,0 +1,165 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from app.core.security import validate_password
|
||||
from app.models.masters import User
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task4_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task4_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str = "admin@poona.demo") -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||
assert res.status_code == 200, res.text
|
||||
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
|
||||
|
||||
def test_validate_password_unit():
|
||||
# 1. Short password (< 8)
|
||||
with pytest.raises(Exception) as exc1:
|
||||
validate_password("Short1", email="user@hospital.com")
|
||||
assert "at least 8 characters" in str(exc1.value)
|
||||
|
||||
# 2. No digits
|
||||
with pytest.raises(Exception) as exc2:
|
||||
validate_password("NoDigitsHere", email="user@hospital.com")
|
||||
assert "at least one letter and at least one digit" in str(exc2.value)
|
||||
|
||||
# 3. No letters
|
||||
with pytest.raises(Exception) as exc3:
|
||||
validate_password("1234567890", email="user@hospital.com")
|
||||
assert "at least one letter and at least one digit" in str(exc3.value)
|
||||
|
||||
# 4. Leading / trailing space
|
||||
with pytest.raises(Exception) as exc4a:
|
||||
validate_password(" Secret123", email="user@hospital.com")
|
||||
assert "space" in str(exc4a.value)
|
||||
|
||||
with pytest.raises(Exception) as exc4b:
|
||||
validate_password("Secret123 ", email="user@hospital.com")
|
||||
assert "space" in str(exc4b.value)
|
||||
|
||||
# 5. Blocklisted passwords
|
||||
for bad in ("12345678", "password", "password1", "qwerty123", "admin123", "welcome1"):
|
||||
with pytest.raises(Exception) as exc5:
|
||||
validate_password(bad, email="user@hospital.com")
|
||||
assert "easily guessable" in str(exc5.value) or "at least 8" in str(exc5.value) or "at least one" in str(exc5.value)
|
||||
|
||||
# 6. Demo password MUST be allowed
|
||||
validate_password("demo@123", email="admin@poona.demo")
|
||||
validate_password("Demo@123", email="admin@poona.demo")
|
||||
|
||||
# 7. Contains email local part (>= 4 chars)
|
||||
with pytest.raises(Exception) as exc7:
|
||||
validate_password("Secureadmin123", email="admin@poona.demo")
|
||||
assert "username" in str(exc7.value).lower()
|
||||
|
||||
# Short local part (< 4 chars) does NOT trigger username check
|
||||
validate_password("Securebio123", email="bio@poona.demo")
|
||||
|
||||
|
||||
def test_api_create_user_password_validation(client, db):
|
||||
headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
# Rejected: no digit
|
||||
res_bad = client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Test User",
|
||||
"email": "test_pw_rule@poona.demo",
|
||||
"password": "NoDigitsPassword",
|
||||
"role": "biomedical",
|
||||
},
|
||||
)
|
||||
assert res_bad.status_code == 422
|
||||
assert "letter and at least one digit" in res_bad.json()["detail"]
|
||||
|
||||
# Rejected: contains email username "tester123"
|
||||
res_username = client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Test User 2",
|
||||
"email": "tester123@poona.demo",
|
||||
"password": "tester123Password1",
|
||||
"role": "biomedical",
|
||||
},
|
||||
)
|
||||
assert res_username.status_code == 422
|
||||
assert "username" in res_username.json()["detail"].lower()
|
||||
|
||||
# Accepted: valid password with letters and numbers
|
||||
res_ok = client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Test User 3",
|
||||
"email": "validuser@poona.demo",
|
||||
"password": "ValidPassword123",
|
||||
"role": "biomedical",
|
||||
},
|
||||
)
|
||||
assert res_ok.status_code == 201
|
||||
user_id = res_ok.json()["id"]
|
||||
|
||||
# Reset password with leading space rejected
|
||||
res_reset_bad = client.post(
|
||||
f"/api/users/{user_id}/reset-password",
|
||||
headers=headers,
|
||||
json={"new_password": " LeadingSpace123"},
|
||||
)
|
||||
assert res_reset_bad.status_code == 422
|
||||
assert "space" in res_reset_bad.json()["detail"]
|
||||
|
||||
# Reset password with valid password succeeds
|
||||
res_reset_ok = client.post(
|
||||
f"/api/users/{user_id}/reset-password",
|
||||
headers=headers,
|
||||
json={"new_password": "NewValidSecret456"},
|
||||
)
|
||||
assert res_reset_ok.status_code == 200
|
||||
|
||||
|
||||
def test_api_change_password_validation(client, db):
|
||||
# Log in as bio user
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
# Reject new == current
|
||||
res_same = client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=bio_headers,
|
||||
json={"current_password": "Demo@123", "new_password": "Demo@123"},
|
||||
)
|
||||
assert res_same.status_code == 422
|
||||
assert res_same.json()["detail"] == "New password must be different."
|
||||
|
||||
# Reject trailing space
|
||||
res_space = client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=bio_headers,
|
||||
json={"current_password": "Demo@123", "new_password": "NewSecretPass1 "},
|
||||
)
|
||||
assert res_space.status_code == 422
|
||||
assert "space" in res_space.json()["detail"]
|
||||
|
||||
# Reject blocklisted password
|
||||
res_block = client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=bio_headers,
|
||||
json={"current_password": "Demo@123", "new_password": "password1"},
|
||||
)
|
||||
assert res_block.status_code == 422
|
||||
|
||||
# Accept valid change
|
||||
res_ok = client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=bio_headers,
|
||||
json={"current_password": "Demo@123", "new_password": "BrandNewSecret789"},
|
||||
)
|
||||
assert res_ok.status_code == 200
|
||||
assert res_ok.json()["message"] == "Password changed successfully."
|
||||
@@ -0,0 +1,133 @@
|
||||
import pytest
|
||||
from app.core.security import hash_password
|
||||
from app.models import Asset, Department, User
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.scoping import DepartmentScope, resolve_department_scope
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task6_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task6_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||
assert res.status_code == 200, res.text
|
||||
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
|
||||
|
||||
def test_resolve_department_scope_rules():
|
||||
# Admin is unconstrained
|
||||
admin_user = User(role="system_admin", department_id=None)
|
||||
scope = resolve_department_scope(admin_user, requested_dept_id=5)
|
||||
assert scope == DepartmentScope(is_unconstrained=True, department_id=5, is_empty=False)
|
||||
|
||||
# Department user with department_id=None is empty
|
||||
unassigned = User(role="department_user", department_id=None)
|
||||
scope_empty = resolve_department_scope(unassigned, requested_dept_id=5)
|
||||
assert scope_empty == DepartmentScope(is_unconstrained=False, department_id=None, is_empty=True)
|
||||
|
||||
# Department user with assigned department cannot be overridden
|
||||
assigned = User(role="department_user", department_id=1)
|
||||
scope_assigned = resolve_department_scope(assigned, requested_dept_id=99)
|
||||
assert scope_assigned == DepartmentScope(is_unconstrained=False, department_id=1, is_empty=False)
|
||||
|
||||
|
||||
def test_unassigned_department_user_sees_zero_records(client, db):
|
||||
# Create a department_user with department_id = None
|
||||
email = "unassigned_dept_user@poona.demo"
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
user = User(
|
||||
email=email,
|
||||
name="Unassigned Dept User",
|
||||
password_hash=hash_password("Demo@123"),
|
||||
role="department_user",
|
||||
department_id=None,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
else:
|
||||
user.department_id = None
|
||||
db.commit()
|
||||
|
||||
headers = _auth_headers(client, email)
|
||||
|
||||
# 1. Dashboard summary has all-zero counters
|
||||
dash_res = client.get("/api/dashboard/summary", headers=headers)
|
||||
assert dash_res.status_code == 200
|
||||
dash_data = dash_res.json()
|
||||
kpis = dash_data["kpis"]
|
||||
assert kpis["total_assets"] == 0
|
||||
assert kpis["assets_under_repair"] == 0
|
||||
assert kpis["open_complaints"] == 0
|
||||
assert kpis["pm_due_this_month"] == 0
|
||||
assert kpis["calibrations_due"] == 0
|
||||
assert kpis["contracts_expiring"] == 0
|
||||
assert kpis["equipment_on_demo"] == 0
|
||||
assert len(dash_data["recent_complaints"]) == 0
|
||||
assert len(dash_data["needs_attention"]) == 0
|
||||
|
||||
# 2. Global search returns 0 assets and 0 complaints
|
||||
search_res = client.get("/api/search?q=card", headers=headers)
|
||||
assert search_res.status_code == 200
|
||||
search_data = search_res.json()
|
||||
assert search_data["assets"] == []
|
||||
assert search_data["complaints"] == []
|
||||
|
||||
# 3. All accessible report endpoints return 0 rows for this user
|
||||
report_keys = [
|
||||
"equipment-inventory",
|
||||
"monthly-maintenance",
|
||||
"monthly-department",
|
||||
"breakdown-complaints",
|
||||
"pm-compliance",
|
||||
"calibration-due",
|
||||
"contracts-warranty",
|
||||
"demo-equipment",
|
||||
]
|
||||
for key in report_keys:
|
||||
rep_res = client.get(f"/api/reports/{key}", headers=headers)
|
||||
assert rep_res.status_code == 200, f"{key} failed: {rep_res.text}"
|
||||
body = rep_res.json()
|
||||
assert len(body["rows"]) == 0, f"Expected 0 rows for {key}, got {len(body['rows'])}"
|
||||
|
||||
|
||||
def test_assigned_department_user_scoping_ignores_query_param(client, db):
|
||||
# Get two distinct departments that have assets
|
||||
depts = db.query(Department).filter(Department.is_active.is_(True)).all()
|
||||
assert len(depts) >= 2
|
||||
dept1, dept2 = depts[0], depts[1]
|
||||
|
||||
email = "dept1_scoped_user@poona.demo"
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
user = User(
|
||||
email=email,
|
||||
name="Dept1 Scoped User",
|
||||
password_hash=hash_password("Demo@123"),
|
||||
role="department_user",
|
||||
department_id=dept1.id,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
else:
|
||||
user.department_id = dept1.id
|
||||
db.commit()
|
||||
|
||||
headers = _auth_headers(client, email)
|
||||
|
||||
# Calling with ?department_id=dept2.id MUST be ignored and scoped strictly to dept1
|
||||
res = client.get(
|
||||
f"/api/reports/equipment-inventory?department_id={dept2.id}",
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["filters_applied"]["department_id"] == dept1.id
|
||||
for row in body["rows"]:
|
||||
assert row["department_id"] == dept1.id
|
||||
@@ -0,0 +1,91 @@
|
||||
import pytest
|
||||
from app.models import User
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task7_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task7_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def test_token_invalidation_on_change_password_and_admin_reset(client, db):
|
||||
# 1. Login as user and save the initial token
|
||||
user_email = "bio@poona.demo"
|
||||
login_res = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user_email, "password": "Demo@123"},
|
||||
)
|
||||
assert login_res.status_code == 200
|
||||
old_token = login_res.json()["access_token"]
|
||||
|
||||
# Verify initial token works
|
||||
me_res1 = client.get(
|
||||
"/api/auth/me",
|
||||
headers={"Authorization": f"Bearer {old_token}"},
|
||||
)
|
||||
assert me_res1.status_code == 200
|
||||
assert me_res1.json()["email"] == user_email
|
||||
|
||||
# 2. Call POST /api/auth/change-password
|
||||
change_res = client.post(
|
||||
"/api/auth/change-password",
|
||||
headers={"Authorization": f"Bearer {old_token}"},
|
||||
json={"current_password": "Demo@123", "new_password": "NewSecurePass99"},
|
||||
)
|
||||
assert change_res.status_code == 200, change_res.text
|
||||
change_data = change_res.json()
|
||||
assert "access_token" in change_data
|
||||
assert change_data["token_type"] == "bearer"
|
||||
new_token = change_data["access_token"]
|
||||
|
||||
# 3. Assert the old token now gets 401 on an authenticated endpoint
|
||||
old_token_res = client.get(
|
||||
"/api/auth/me",
|
||||
headers={"Authorization": f"Bearer {old_token}"},
|
||||
)
|
||||
assert old_token_res.status_code == 401
|
||||
assert "Token has been invalidated" in old_token_res.json()["detail"]
|
||||
|
||||
# 4. Assert the new token returned by change-password works
|
||||
new_token_res = client.get(
|
||||
"/api/auth/me",
|
||||
headers={"Authorization": f"Bearer {new_token}"},
|
||||
)
|
||||
assert new_token_res.status_code == 200
|
||||
assert new_token_res.json()["email"] == user_email
|
||||
|
||||
# 5. Login as admin, reset that user's password
|
||||
admin_login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "admin@poona.demo", "password": "Demo@123"},
|
||||
)
|
||||
assert admin_login.status_code == 200
|
||||
admin_token = admin_login.json()["access_token"]
|
||||
|
||||
target_user = db.query(User).filter(User.email == user_email).first()
|
||||
assert target_user is not None
|
||||
|
||||
reset_res = client.post(
|
||||
f"/api/users/{target_user.id}/reset-password",
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
json={"new_password": "AdminResetPass88"},
|
||||
)
|
||||
assert reset_res.status_code == 200, reset_res.text
|
||||
|
||||
# 6. Assert the user's token now gets 401
|
||||
user_after_reset_res = client.get(
|
||||
"/api/auth/me",
|
||||
headers={"Authorization": f"Bearer {new_token}"},
|
||||
)
|
||||
assert user_after_reset_res.status_code == 401
|
||||
assert "Token has been invalidated" in user_after_reset_res.json()["detail"]
|
||||
|
||||
# 7. Assert the admin's own token is still valid
|
||||
admin_me_res = client.get(
|
||||
"/api/auth/me",
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
)
|
||||
assert admin_me_res.status_code == 200
|
||||
assert admin_me_res.json()["role"] == "system_admin"
|
||||
@@ -0,0 +1,41 @@
|
||||
import subprocess
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_package_target_creates_clean_delivery_zip(tmp_path):
|
||||
repo_root = Path(__file__).resolve().parent.parent.parent
|
||||
zip_path = tmp_path / "poona-ams-delivery.zip"
|
||||
|
||||
# Run git archive command (matching Makefile package target)
|
||||
cmd = ["git", "archive", "--format=zip", f"--output={zip_path}", "HEAD"]
|
||||
res = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True)
|
||||
assert res.returncode == 0, f"git archive failed: {res.stderr}"
|
||||
assert zip_path.exists()
|
||||
|
||||
with zipfile.ZipFile(zip_path, "r") as z:
|
||||
names = z.namelist()
|
||||
assert len(names) > 0
|
||||
|
||||
# Assert no .db database files
|
||||
db_files = [n for n in names if n.endswith(".db") or n.endswith(".sqlite") or n.endswith(".sqlite3")]
|
||||
assert db_files == [], f"Delivery archive must not contain SQLite databases: {db_files}"
|
||||
|
||||
# Assert no frontend dist/ build files
|
||||
dist_files = [n for n in names if "dist/" in n or n.startswith("dist/")]
|
||||
assert dist_files == [], f"Delivery archive must not contain dist/ directory: {dist_files}"
|
||||
|
||||
# Assert no __pycache__ or compiled bytecode
|
||||
pycache_files = [n for n in names if "__pycache__" in n or n.endswith(".pyc")]
|
||||
assert pycache_files == [], f"Delivery archive must not contain __pycache__: {pycache_files}"
|
||||
|
||||
# Assert no node_modules or .venv
|
||||
vendor_files = [n for n in names if "node_modules/" in n or ".venv/" in n]
|
||||
assert vendor_files == [], f"Delivery archive must not contain vendor/env files: {vendor_files}"
|
||||
|
||||
# Assert essential source files are included
|
||||
assert "backend/app/main.py" in names
|
||||
assert "frontend/src/App.tsx" in names
|
||||
assert "Makefile" in names
|
||||
assert "README.md" in names
|
||||
assert ".gitignore" in names
|
||||
@@ -0,0 +1,38 @@
|
||||
from datetime import date, datetime, timezone
|
||||
from app.core.time_utils import format_date, format_datetime, format_duration
|
||||
|
||||
|
||||
def test_format_datetime_none():
|
||||
assert format_datetime(None) is None
|
||||
|
||||
|
||||
def test_format_datetime_utc_to_kolkata():
|
||||
dt = datetime(2025, 3, 15, 10, 30, tzinfo=timezone.utc)
|
||||
assert format_datetime(dt) == "15-Mar-2025 16:00"
|
||||
|
||||
|
||||
def test_format_datetime_naive_assumes_kolkata():
|
||||
dt = datetime(2025, 3, 15, 9, 5)
|
||||
assert format_datetime(dt) == "15-Mar-2025 09:05"
|
||||
|
||||
|
||||
def test_format_date_none():
|
||||
assert format_date(None) is None
|
||||
|
||||
|
||||
def test_format_date_valid():
|
||||
assert format_date(date(2025, 1, 5)) == "05-Jan-2025"
|
||||
|
||||
|
||||
def test_format_duration_none():
|
||||
assert format_duration(None) == "\u2014"
|
||||
|
||||
|
||||
def test_format_duration_values():
|
||||
assert format_duration(0) == "0m"
|
||||
assert format_duration(45) == "45m"
|
||||
assert format_duration(60) == "1h"
|
||||
assert format_duration(90) == "1h 30m"
|
||||
assert format_duration(1440) == "1d"
|
||||
assert format_duration(1445) == "1d 5m"
|
||||
assert format_duration(1505) == "1d 1h 5m"
|
||||
Reference in New Issue
Block a user