initial commit

This commit is contained in:
Antigravity
2026-11-18 18:06:22 +05:30
commit 13556aa423
229 changed files with 58732 additions and 0 deletions
+397
View File
@@ -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