918 lines
40 KiB
Python
918 lines
40 KiB
Python
from datetime import date, datetime, time, timedelta, timezone
|
|
from pathlib import Path
|
|
import random
|
|
import time as pytime
|
|
from PIL import Image, ImageDraw
|
|
from sqlalchemy import text
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ..core.config import settings
|
|
from ..core.db import SessionLocal, engine
|
|
from ..core.security import hash_password
|
|
from ..core.time_utils import KOLKATA, effective_today
|
|
from ..models import (
|
|
Asset,
|
|
Attachment,
|
|
Base,
|
|
CalibrationPlan,
|
|
CalibrationRecord,
|
|
Category,
|
|
Complaint,
|
|
ComplaintEvent,
|
|
Contract,
|
|
DemoEquipment,
|
|
Department,
|
|
DepartmentVisit,
|
|
InsurancePolicy,
|
|
Location,
|
|
PMRecord,
|
|
PMSchedule,
|
|
User,
|
|
Vendor,
|
|
Warranty,
|
|
)
|
|
from ..services.alerts import run_alert_check
|
|
from ..services.coverage import get_coverage
|
|
from ..services.settings_service import ensure_default_settings, get_demo_as_of_date
|
|
|
|
|
|
def _make_minimal_pdf(title: str) -> bytes:
|
|
safe_title = title.replace("(", "").replace(")", "")
|
|
stream = f"BT /F1 14 Tf 50 750 Td ({safe_title}) Tj ET".encode("latin-1", errors="ignore")
|
|
objects = [
|
|
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n",
|
|
b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",
|
|
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\nendobj\n",
|
|
f"4 0 obj\n<< /Length {len(stream)} >>\nstream\n".encode("ascii") + stream + b"\nendstream\nendobj\n",
|
|
b"5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n",
|
|
]
|
|
out = bytearray(b"%PDF-1.4\n")
|
|
offsets = [0]
|
|
for obj in objects:
|
|
offsets.append(len(out))
|
|
out.extend(obj)
|
|
xref_pos = len(out)
|
|
out.extend(f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode("ascii"))
|
|
for off in offsets[1:]:
|
|
out.extend(f"{off:010d} 00000 n \n".encode("ascii"))
|
|
out.extend(
|
|
f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode("ascii")
|
|
)
|
|
return bytes(out)
|
|
|
|
|
|
def _make_placeholder_jpeg(dest: Path, label: str, bg_rgb: tuple[int, int, int]) -> int:
|
|
img = Image.new("RGB", (640, 480), color=bg_rgb)
|
|
draw = ImageDraw.Draw(img)
|
|
draw.rectangle([20, 20, 620, 460], outline=(255, 255, 255), width=3)
|
|
draw.text((40, 200), "XYZ Hospital", fill=(255, 255, 255))
|
|
draw.text((40, 240), label, fill=(240, 240, 240))
|
|
img.save(dest, format="JPEG", quality=80)
|
|
return dest.stat().st_size
|
|
|
|
|
|
def _ist_to_utc(d: date, hour: int = 10, minute: int = 0) -> datetime:
|
|
local_dt = KOLKATA.localize(datetime.combine(d, time(hour, minute)))
|
|
return local_dt.astimezone(timezone.utc)
|
|
|
|
|
|
def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]:
|
|
rng = random.Random(42)
|
|
|
|
# 1. Clear all tables cleanly in reverse dependency order
|
|
for table in reversed(Base.metadata.sorted_tables):
|
|
db.execute(table.delete())
|
|
# Reset SQLite autoincrement counters if sqlite_sequence exists
|
|
try:
|
|
db.execute(text("DELETE FROM sqlite_sequence"))
|
|
except Exception:
|
|
pass
|
|
db.flush()
|
|
db.expunge_all()
|
|
|
|
# 2. Settings (all defaults)
|
|
ensure_default_settings(db)
|
|
|
|
today = effective_today(db)
|
|
now_utc = _ist_to_utc(today, 12, 0) if get_demo_as_of_date(db) else datetime.now(timezone.utc)
|
|
|
|
# 3. Departments (8)
|
|
dept_specs = [
|
|
("Intensive Care Unit", "ICU", "Medical and surgical intensive care beds"),
|
|
("Operation Theatre", "OT", "Main and modular surgical suites"),
|
|
("Radiology & Imaging", "RAD", "CT, MRI, Ultrasound, and X-Ray"),
|
|
("Cardiology", "CARD", "Cath lab and cardiac diagnostics"),
|
|
("Emergency & Trauma", "EMER", "24x7 casualty and trauma care"),
|
|
("Pathology & Lab", "LAB", "Clinical biochemistry and hematology"),
|
|
("Neonatal ICU", "NICU", "Neonatal intensive care and warmers"),
|
|
("Dialysis Unit", "DIAL", "Hemodialysis and RO water treatment"),
|
|
]
|
|
departments: list[Department] = []
|
|
for name, code, desc in dept_specs:
|
|
d = Department(name=name, code=code, description=desc, is_active=True)
|
|
db.add(d)
|
|
departments.append(d)
|
|
db.flush()
|
|
|
|
# 4. Locations (20)
|
|
loc_specs = [
|
|
(0, "ICU Bay A", "2nd Floor - East Wing"),
|
|
(0, "ICU Bay B", "2nd Floor - East Wing"),
|
|
(0, "ICU Isolation Room 1", "2nd Floor - East Wing"),
|
|
(1, "Modular OT 1", "3rd Floor - Central Block"),
|
|
(1, "Modular OT 2", "3rd Floor - Central Block"),
|
|
(1, "OT Recovery Suite", "3rd Floor - Central Block"),
|
|
(2, "CT Scan Room", "Ground Floor - West Wing"),
|
|
(2, "Digital X-Ray Suite", "Ground Floor - West Wing"),
|
|
(2, "Ultrasound Room 2", "Ground Floor - West Wing"),
|
|
(3, "Cath Lab 1", "4th Floor - Cardiac Block"),
|
|
(3, "Echo & TMT Room", "4th Floor - Cardiac Block"),
|
|
(4, "Trauma Resuscitation Bay", "Ground Floor - Main Gate"),
|
|
(4, "Emergency Observation Ward", "Ground Floor - Main Gate"),
|
|
(5, "Biochemistry Analyzer Lab", "1st Floor - Diagnostic Wing"),
|
|
(5, "Hematology & Blood Bank", "1st Floor - Diagnostic Wing"),
|
|
(6, "NICU Level 3 Bay", "2nd Floor - Maternity Wing"),
|
|
(6, "NICU Step-Down Unit", "2nd Floor - Maternity Wing"),
|
|
(7, "Dialysis Station 1-6", "1st Floor - Renal Wing"),
|
|
(7, "Dialysis Station 7-12", "1st Floor - Renal Wing"),
|
|
(7, "RO Water Plant Room", "1st Floor - Renal Wing"),
|
|
]
|
|
locations: list[Location] = []
|
|
locs_by_dept: dict[int, list[Location]] = {d.id: [] for d in departments}
|
|
for dept_idx, lname, floor in loc_specs:
|
|
dept = departments[dept_idx]
|
|
loc = Location(department_id=dept.id, name=lname, floor_wing=floor, is_active=True)
|
|
db.add(loc)
|
|
locations.append(loc)
|
|
locs_by_dept[dept.id].append(loc)
|
|
db.flush()
|
|
|
|
# 5. Categories (8) with realistic default_useful_life_years
|
|
cat_specs = [
|
|
("Life Support & Ventilators", "ICU ventilators, CPAP/BiPAP, anesthesia systems", 10),
|
|
("Patient Monitoring", "Multipara monitors, pulse oximeters, central stations", 8),
|
|
("Diagnostic Imaging", "X-Ray, C-Arm, ultrasound, CT/MRI auxiliaries", 12),
|
|
("Surgical & OT Equipment", "Electrosurgical cautery, OT tables, OT lights", 10),
|
|
("Laboratory Analyzers", "Biochemistry, hematology, blood gas analyzers", 8),
|
|
("Infusion & Dialysis", "Syringe pumps, infusion pumps, hemodialysis machines", 7),
|
|
("Sterilization & CSSD", "Autoclaves, ETO sterilizers, washer-disinfectors", 12),
|
|
("Emergency & Resuscitation", "Defibrillators, crash carts, suction apparatus", 8),
|
|
]
|
|
categories: list[Category] = []
|
|
for cname, cdesc, clife in cat_specs:
|
|
c = Category(
|
|
name=cname,
|
|
description=cdesc,
|
|
default_useful_life_years=clife,
|
|
is_active=True,
|
|
)
|
|
db.add(c)
|
|
categories.append(c)
|
|
db.flush()
|
|
|
|
# 6. Vendors (12)
|
|
vendor_specs = [
|
|
("Philips Healthcare India", "oem", "Arun Mehta", "+91-20-66201100", "service.west@philips-demo.in", "Pune, MH"),
|
|
("GE HealthCare Medical Systems", "oem", "Sanjay Verma", "+91-20-66202200", "support@gehc-demo.in", "Mumbai, MH"),
|
|
("Mindray Medical India", "oem", "Rohan Kapoor", "+91-22-40203300", "service@mindray-demo.in", "Mumbai, MH"),
|
|
("MedTech Pune Distributors", "supplier", "Prashant Joshi", "+91-9822011223", "sales@medtechpune.in", "Deccan Gymkhana, Pune"),
|
|
("Sahyadri Medical Supplies", "supplier", "Manish Patwardhan", "+91-9823044556", "orders@sahyadrimed.in", "Kothrud, Pune"),
|
|
("Deccan Bio-Equipments", "supplier", "Kavita Gokhale", "+91-9890077889", "info@deccanbio.in", "Shivajinagar, Pune"),
|
|
("Apex Biomedical Services", "service_provider", "Nitin Kulkarni", "+91-9765012345", "amc@apexbiomed.in", "Pimpri, Pune"),
|
|
("Precision MedCare Engineering", "service_provider", "Deepak Rao", "+91-9850098765", "ops@precisionmedcare.in", "Hadapsar, Pune"),
|
|
("NABL Metrology & CalLabs Pune", "calibration_agency", "Dr. Sunita Deshpande", "+91-20-25441234", "cal@nablcallabs.in", "Bhosari MIDC, Pune"),
|
|
("Western India Calibration Lab", "calibration_agency", "Mahesh Pawar", "+91-20-24335678", "qa@wical.in", "Satara Road, Pune"),
|
|
("New India Assurance Co.", "insurer", "Smita Kale", "+91-20-26128899", "corporate@nia-demo.in", "MG Road, Pune"),
|
|
("Bajaj Allianz General Insurance", "insurer", "Vivek Deshmukh", "+91-20-66026602", "healthassets@bagic-demo.in", "Yerwada, Pune"),
|
|
]
|
|
vendors: list[Vendor] = []
|
|
vendors_by_type: dict[str, list[Vendor]] = {}
|
|
for vname, vtype, cp, ph, em, addr in vendor_specs:
|
|
v = Vendor(
|
|
name=vname,
|
|
vendor_type=vtype,
|
|
contact_person=cp,
|
|
phone=ph,
|
|
email=em,
|
|
address=addr,
|
|
is_active=True,
|
|
)
|
|
db.add(v)
|
|
vendors.append(v)
|
|
vendors_by_type.setdefault(vtype, []).append(v)
|
|
db.flush()
|
|
|
|
# 7. Users (11: 5 demo + 6 realistic hospital staff)
|
|
demo_pw_hash = hash_password("Demo@123")
|
|
user_specs = [
|
|
("Dr. Rajesh Kulkarni", "admin@xyz.demo", "system_admin", None),
|
|
("Suresh Deshmukh", "bio@xyz.demo", "biomedical", None),
|
|
("Sister Kavita Joshi", "dept@xyz.demo", "department_user", departments[0].id), # ICU
|
|
("Dr. Anjali Gokhale", "mgmt@xyz.demo", "management", None),
|
|
("Priya Patwardhan", "coord@xyz.demo", "coordinator", None),
|
|
("Vikram Shinde", "vikram.shinde@xyz.demo", "biomedical", None),
|
|
("Sneha Kulkarni", "sneha.kulkarni@xyz.demo", "biomedical", None),
|
|
("Dr. Amit Bhosale", "dr.amit.bhosale@xyz.demo", "department_user", departments[1].id), # OT
|
|
("Meera Nair", "meera.nair@xyz.demo", "department_user", departments[2].id), # RAD
|
|
("Rohit Deshpande", "rohit.deshpande@xyz.demo", "department_user", departments[3].id), # CARD
|
|
("Neha Chavan", "neha.chavan@xyz.demo", "coordinator", None),
|
|
]
|
|
users: list[User] = []
|
|
for uname, uemail, urole, udept in user_specs:
|
|
u = User(
|
|
name=uname,
|
|
email=uemail,
|
|
password_hash=demo_pw_hash,
|
|
role=urole,
|
|
department_id=udept,
|
|
is_active=True,
|
|
)
|
|
db.add(u)
|
|
users.append(u)
|
|
db.flush()
|
|
|
|
admin_user = users[0]
|
|
bio_users = [users[1], users[5], users[6]]
|
|
dept_users = [users[2], users[7], users[8], users[9]]
|
|
coord_users = [users[4], users[10]]
|
|
|
|
# 8. Assets (60)
|
|
equipment_catalog = [
|
|
("ICU Ventilator Servo-i", 0, 0, True, True, 950000.0),
|
|
("Multipara Patient Monitor MP50", 1, 0, True, True, 380000.0),
|
|
("Syringe Infusion Pump SP-500", 5, 0, True, False, 65000.0),
|
|
("Biphasic Defibrillator DFM100", 7, 4, True, True, 320000.0),
|
|
("Anesthesia Workstation Aespire", 0, 1, True, True, 1150000.0),
|
|
("Electrosurgical Cautery Unit", 3, 1, True, False, 260000.0),
|
|
("LED Dual-Dome OT Light", 3, 1, False, False, 480000.0),
|
|
("64-Slice CT Scanner Optima", 2, 2, True, True, 12500000.0),
|
|
("C-Arm Fluoroscopy System", 2, 1, True, True, 3400000.0),
|
|
("Color Doppler Ultrasound", 2, 2, False, True, 2600000.0),
|
|
("12-Channel Digital ECG Machine", 1, 3, True, False, 140000.0),
|
|
("1.5T MRI Imaging System", 2, 2, False, True, 18500000.0),
|
|
("Automated Biochemistry Analyzer", 4, 5, True, True, 1450000.0),
|
|
("5-Part Hematology Analyzer", 4, 5, True, True, 980000.0),
|
|
("ABG Blood Gas Analyzer", 4, 0, True, False, 420000.0),
|
|
("Infant Radiant Warmer", 0, 6, True, False, 210000.0),
|
|
("Neonatal Phototherapy Unit", 0, 6, False, False, 125000.0),
|
|
("Hemodialysis Machine 4008S", 5, 7, True, True, 890000.0),
|
|
("High-Pressure Steam Autoclave", 6, 1, True, True, 450000.0),
|
|
("Portable Suction Apparatus", 7, 4, False, False, 180000.0),
|
|
]
|
|
suppliers_and_oems = vendors_by_type["supplier"] + vendors_by_type["oem"]
|
|
dept_counters: dict[str, int] = {}
|
|
assets: list[Asset] = []
|
|
rented_indices = {45, 46, 47, 48, 49, 50}
|
|
fully_dep_indices = {40, 41}
|
|
|
|
for i in range(60):
|
|
base_name, cat_idx, default_dept_idx, req_cal, ins_app, base_val = equipment_catalog[i % len(equipment_catalog)]
|
|
dept_idx = default_dept_idx if i < 20 else rng.randrange(len(departments))
|
|
dept = departments[dept_idx]
|
|
dept_counters[dept.code] = dept_counters.get(dept.code, 0) + 1
|
|
asset_code = f"PHRC-{dept.code}-{dept_counters[dept.code]:04d}"
|
|
loc = rng.choice(locs_by_dept[dept.id])
|
|
supplier = rng.choice(suppliers_and_oems)
|
|
|
|
if i < 10:
|
|
# 10 latest equipment purchased in the last 12 months
|
|
purchase_date = today - timedelta(days=30 + i * 26)
|
|
install_date = purchase_date + timedelta(days=7)
|
|
elif i in fully_dep_indices:
|
|
# Fully depreciated assets (> 10 years old)
|
|
purchase_date = today - timedelta(days=12 * 365 + (i - 40) * 180)
|
|
install_date = purchase_date + timedelta(days=15)
|
|
else:
|
|
years_ago = rng.randint(2, 8)
|
|
purchase_date = today - timedelta(days=years_ago * 365 + rng.randint(15, 280))
|
|
install_date = purchase_date + timedelta(days=rng.randint(7, 30))
|
|
|
|
# Status distribution: mostly in_service, a few under_repair / out_of_service / condemned
|
|
if i in (5, 19, 31, 44):
|
|
status_val = "under_repair"
|
|
elif i in (52, 57):
|
|
status_val = "out_of_service"
|
|
elif i in (58, 59):
|
|
status_val = "condemned"
|
|
else:
|
|
status_val = "in_service"
|
|
|
|
criticality = "critical" if (cat_idx in (0, 2, 3, 7) or i % 3 == 0) else "non_critical"
|
|
needs_cal = True if i < 22 else req_cal
|
|
needs_ins = True if i < 26 else ins_app
|
|
|
|
is_rented = i in rented_indices
|
|
pv = None if is_rented else round(base_val * rng.uniform(0.95, 1.08), 0)
|
|
acq_mode = "rented" if is_rented else "purchased"
|
|
if is_rented:
|
|
m_rent = round(base_val * rng.uniform(0.022, 0.03), -2)
|
|
elif i < 25:
|
|
# 25 owned assets with monthly_rent quotes for buy-vs-rent comparison
|
|
m_rent = round((pv or base_val) * rng.uniform(0.022, 0.032), -2)
|
|
else:
|
|
m_rent = None
|
|
|
|
cat_life = categories[cat_idx].default_useful_life_years or 10
|
|
u_life = None if is_rented else (10 if i in fully_dep_indices else cat_life)
|
|
salv_pct = None if is_rented else (5.0 if i % 4 != 0 else 10.0)
|
|
dep_method = None if is_rented else ("straight_line" if i % 3 != 2 else "written_down")
|
|
|
|
a = Asset(
|
|
asset_code=asset_code,
|
|
serial_no=f"SN-{2016 + (i % 9)}-{10000 + i * 37}",
|
|
name=f"{base_name}" if i < 20 else f"{base_name} #{(i // 20) + 1}",
|
|
category_id=categories[cat_idx].id,
|
|
department_id=dept.id,
|
|
location_id=loc.id,
|
|
supplier_id=supplier.id,
|
|
purchase_value=pv,
|
|
acquisition_mode=acq_mode,
|
|
monthly_rent=m_rent,
|
|
useful_life_years=u_life,
|
|
salvage_pct=salv_pct,
|
|
depreciation_method=dep_method,
|
|
purchase_date=purchase_date,
|
|
installation_date=install_date,
|
|
status=status_val,
|
|
criticality=criticality,
|
|
requires_calibration=needs_cal,
|
|
insurance_applicable=needs_ins,
|
|
remarks="Procured under XYZ Hospital capital equipment budget." if not is_rented else "Leased medical equipment on monthly rental.",
|
|
created_by_id=admin_user.id,
|
|
updated_by_id=admin_user.id,
|
|
)
|
|
db.add(a)
|
|
assets.append(a)
|
|
db.flush()
|
|
|
|
# 9. Contracts (35 total: 3 expiring <=30d, 1 <=5d, 1 expired, 1 renewed chain w/ is_superseded=True)
|
|
service_providers = vendors_by_type["service_provider"] + vendors_by_type["oem"]
|
|
contracts: list[Contract] = []
|
|
# Renewed chain: old superseded contract (#0) + active renewed contract (#1)
|
|
a0_pv = assets[0].purchase_value or 950000.0
|
|
old_c = Contract(
|
|
asset_id=assets[0].id,
|
|
contract_type="CMC",
|
|
provider_id=service_providers[0].id,
|
|
start_date=today - timedelta(days=400),
|
|
end_date=today - timedelta(days=35),
|
|
contract_value=round(a0_pv * 0.10, -2),
|
|
coverage_period_text="1 Year",
|
|
renewed_from_id=None,
|
|
is_superseded=True,
|
|
remarks="Previous year CMC superseded on renewal.",
|
|
created_by_id=coord_users[0].id,
|
|
updated_by_id=coord_users[0].id,
|
|
)
|
|
db.add(old_c)
|
|
db.flush()
|
|
contracts.append(old_c)
|
|
|
|
new_c = Contract(
|
|
asset_id=assets[0].id,
|
|
contract_type="CMC",
|
|
provider_id=service_providers[0].id,
|
|
start_date=today - timedelta(days=34),
|
|
end_date=today + timedelta(days=331),
|
|
contract_value=round(a0_pv * 0.11, -2),
|
|
coverage_period_text="1 Year",
|
|
renewed_from_id=old_c.id,
|
|
is_superseded=False,
|
|
remarks="Renewed annual comprehensive maintenance contract.",
|
|
created_by_id=coord_users[0].id,
|
|
updated_by_id=coord_users[0].id,
|
|
)
|
|
db.add(new_c)
|
|
contracts.append(new_c)
|
|
|
|
# 1 expiring <= 5d (idx 2), 3 expiring <= 30d (idx 3, 4, 5), 1 expired (idx 16), rest active > 45d
|
|
special_end_offsets = {
|
|
2: 3, # <= 5 days
|
|
3: 11, # <= 30 days
|
|
4: 19, # <= 30 days
|
|
5: 27, # <= 30 days
|
|
16: -14, # expired -> out_of_contract
|
|
}
|
|
for idx in range(1, 34):
|
|
asset = assets[idx]
|
|
offset = special_end_offsets.get(idx, rng.randint(50, 340))
|
|
end_d = today + timedelta(days=offset)
|
|
start_d = end_d - timedelta(days=365)
|
|
ctype = ("AMC" if idx % 2 == 0 else "CMC") if idx < 10 else rng.choice(["AMC", "CMC", "AMC", "OTHER"])
|
|
pv_base = asset.purchase_value or 500000.0
|
|
if ctype == "AMC":
|
|
cval = round(pv_base * rng.uniform(0.055, 0.095), -2)
|
|
elif ctype == "CMC":
|
|
cval = round(pv_base * rng.uniform(0.085, 0.135), -2)
|
|
else:
|
|
cval = round(pv_base * rng.uniform(0.04, 0.07), -2)
|
|
c = Contract(
|
|
asset_id=asset.id,
|
|
contract_type=ctype,
|
|
provider_id=rng.choice(service_providers).id,
|
|
start_date=start_d,
|
|
end_date=end_d,
|
|
contract_value=cval,
|
|
coverage_period_text="1 Year",
|
|
renewed_from_id=None,
|
|
is_superseded=False,
|
|
remarks=f"{ctype} maintenance coverage for {asset.asset_code}.",
|
|
created_by_id=coord_users[idx % 2].id,
|
|
updated_by_id=coord_users[idx % 2].id,
|
|
)
|
|
db.add(c)
|
|
contracts.append(c)
|
|
db.flush()
|
|
|
|
active_contract_by_asset: dict[int, Contract] = {
|
|
c.asset_id: c for c in contracts if not c.is_superseded and c.end_date >= today
|
|
}
|
|
|
|
# 10. Warranties (20 total: 4 expiring <= 30d)
|
|
for idx in range(20):
|
|
asset = assets[idx]
|
|
if idx < 4:
|
|
end_d = today + timedelta(days=[5, 14, 22, 28][idx])
|
|
dur = 24
|
|
start_d = end_d - timedelta(days=dur * 30)
|
|
else:
|
|
dur = rng.choice([12, 24, 36])
|
|
end_d = today + timedelta(days=rng.randint(60, 500))
|
|
start_d = end_d - timedelta(days=dur * 30)
|
|
w = Warranty(
|
|
asset_id=asset.id,
|
|
duration_months=dur,
|
|
start_date=start_d,
|
|
end_date=end_d,
|
|
provider_id=asset.supplier_id,
|
|
remarks="OEM standard warranty.",
|
|
created_by_id=coord_users[0].id,
|
|
updated_by_id=coord_users[0].id,
|
|
)
|
|
db.add(w)
|
|
db.flush()
|
|
|
|
# 11. Insurance Policies (25 total: 2 expiring soon)
|
|
insurers = vendors_by_type["insurer"]
|
|
insured_assets = [a for a in assets if a.insurance_applicable][:25]
|
|
for idx, asset in enumerate(insured_assets):
|
|
if idx == 0:
|
|
end_d = today + timedelta(days=9)
|
|
elif idx == 1:
|
|
end_d = today + timedelta(days=23)
|
|
else:
|
|
end_d = today + timedelta(days=rng.randint(45, 330))
|
|
start_d = end_d - timedelta(days=365)
|
|
pol = InsurancePolicy(
|
|
asset_id=asset.id,
|
|
insurer_id=insurers[idx % len(insurers)].id,
|
|
policy_no=f"PHRC-INS-{today.year}-{1001 + idx}",
|
|
start_date=start_d,
|
|
end_date=end_d,
|
|
coverage_amount=round((asset.purchase_value or 500000.0) * 0.9, 2),
|
|
remarks="All-risk biomedical equipment insurance.",
|
|
created_by_id=coord_users[idx % 2].id,
|
|
updated_by_id=coord_users[idx % 2].id,
|
|
)
|
|
db.add(pol)
|
|
db.flush()
|
|
|
|
# 12. Calibration Plans (20) + historical completed records + open (upcoming/due/overdue) records
|
|
cal_agencies = vendors_by_type["calibration_agency"]
|
|
cal_assets = [a for a in assets if a.requires_calibration][:20]
|
|
for idx, asset in enumerate(cal_assets):
|
|
freq = 6 if idx % 2 == 0 else 12
|
|
per_year = 12 // freq
|
|
agency = cal_agencies[idx % len(cal_agencies)]
|
|
# Make 3 overdue, 4 due within 15 days, 13 upcoming
|
|
if idx < 3:
|
|
next_due = today - timedelta(days=4 + idx * 5)
|
|
elif idx < 7:
|
|
next_due = today + timedelta(days=2 + (idx - 3) * 3)
|
|
else:
|
|
next_due = today + timedelta(days=25 + idx * 7)
|
|
|
|
plan = CalibrationPlan(
|
|
asset_id=asset.id,
|
|
frequency_months=freq,
|
|
calibrations_per_year=per_year,
|
|
agency_id=agency.id,
|
|
approved_by_id=bio_users[0].id,
|
|
approved_on=today - timedelta(days=400),
|
|
next_due_date=next_due,
|
|
is_active=True,
|
|
created_by_id=bio_users[0].id,
|
|
updated_by_id=bio_users[0].id,
|
|
)
|
|
db.add(plan)
|
|
db.flush()
|
|
|
|
# Historical completed record (1-2 cycles back)
|
|
prev_due = next_due - timedelta(days=freq * 30)
|
|
if prev_due < today:
|
|
db.add(
|
|
CalibrationRecord(
|
|
asset_id=asset.id,
|
|
plan_id=plan.id,
|
|
due_date=prev_due,
|
|
completed_date=prev_due - timedelta(days=rng.randint(0, 3)),
|
|
agency_id=agency.id,
|
|
certificate_no=f"CAL-{today.year - 1}-{400 + idx}",
|
|
remarks="Calibrated within NABL permissible tolerance.",
|
|
status="completed",
|
|
created_by_id=bio_users[idx % len(bio_users)].id,
|
|
updated_by_id=bio_users[idx % len(bio_users)].id,
|
|
)
|
|
)
|
|
# Current open calibration record (status=None so upcoming/due/overdue is computed dynamically)
|
|
db.add(
|
|
CalibrationRecord(
|
|
asset_id=asset.id,
|
|
plan_id=plan.id,
|
|
due_date=next_due,
|
|
completed_date=None,
|
|
agency_id=agency.id,
|
|
certificate_no=None,
|
|
remarks="Scheduled calibration cycle.",
|
|
status=None,
|
|
created_by_id=bio_users[0].id,
|
|
updated_by_id=bio_users[0].id,
|
|
)
|
|
)
|
|
db.flush()
|
|
|
|
# 13. PM Schedules (45: 60% in_house=27, 40% outsourced=18) + 6 months records + 4 due this month + 3 overdue
|
|
for idx in range(45):
|
|
asset = assets[idx]
|
|
mode = "in_house" if idx < 27 else "outsourced"
|
|
freq = 3 if idx % 3 == 0 else 6
|
|
contract = active_contract_by_asset.get(asset.id)
|
|
provider_id = contract.provider_id if (mode == "outsourced" and contract) else (
|
|
service_providers[idx % len(service_providers)].id if mode == "outsourced" else None
|
|
)
|
|
# 3 overdue, 4 due this month (within next 12 days), rest upcoming
|
|
if idx < 3:
|
|
next_planned = today - timedelta(days=3 + idx * 5)
|
|
elif idx < 7:
|
|
next_planned = today + timedelta(days=1 + (idx - 3) * 3)
|
|
else:
|
|
next_planned = today + timedelta(days=22 + (idx % 60))
|
|
|
|
inhouse_cost = (
|
|
round(max(2500.0, min(25000.0, (asset.purchase_value or 350000.0) * 0.008)), -2)
|
|
if mode == "in_house"
|
|
else None
|
|
)
|
|
|
|
sched = PMSchedule(
|
|
asset_id=asset.id,
|
|
service_mode=mode,
|
|
frequency_months=freq,
|
|
responsible_team="In-House Biomedical Team" if mode == "in_house" else None,
|
|
provider_id=provider_id,
|
|
contract_id=contract.id if (mode == "outsourced" and contract) else None,
|
|
cost_per_visit=inhouse_cost,
|
|
next_planned_date=next_planned,
|
|
is_active=True,
|
|
created_by_id=bio_users[0].id,
|
|
updated_by_id=bio_users[0].id,
|
|
)
|
|
db.add(sched)
|
|
db.flush()
|
|
|
|
# Historical completed PM records over past 6 months
|
|
for cycle in (1, 2):
|
|
hist_date = today - timedelta(days=cycle * 90 + (idx % 15))
|
|
db.add(
|
|
PMRecord(
|
|
schedule_id=sched.id,
|
|
asset_id=asset.id,
|
|
planned_date=hist_date,
|
|
completed_date=hist_date + timedelta(days=rng.randint(0, 2)),
|
|
status="completed",
|
|
service_details="Filter cleaning, electrical safety test, and functional verification.",
|
|
remarks="Passed all PM checklist points.",
|
|
created_by_id=bio_users[idx % len(bio_users)].id,
|
|
updated_by_id=bio_users[idx % len(bio_users)].id,
|
|
)
|
|
)
|
|
# Current open PM record (status=None; upcoming/due/overdue computed dynamically)
|
|
db.add(
|
|
PMRecord(
|
|
schedule_id=sched.id,
|
|
asset_id=asset.id,
|
|
planned_date=next_planned,
|
|
completed_date=None,
|
|
status=None,
|
|
service_details=None,
|
|
remarks="Scheduled preventive maintenance.",
|
|
created_by_id=bio_users[0].id,
|
|
updated_by_id=bio_users[0].id,
|
|
)
|
|
)
|
|
db.flush()
|
|
|
|
# 14. Complaints (30: 70% non-critical=21, 9 critical; 22 closed, 4 in_progress, 4 open)
|
|
# Must include: 1 critical open > 24h, 1 spanning month boundary, 6 spares, 5 CE
|
|
complaints: list[Complaint] = []
|
|
issue_descriptions = [
|
|
"Display flickering intermittently during monitoring",
|
|
"Airway pressure sensor alarm triggering falsely",
|
|
"Battery backup not holding charge during transport",
|
|
"Touchscreen unresponsive on main control panel",
|
|
"Power supply fuse blown after voltage fluctuation",
|
|
"Flow sensor calibration error on self-test",
|
|
"Suction vacuum pressure dropping below threshold",
|
|
"ECG lead wire connector loose at patient cable port",
|
|
"Temperature probe reading drift observed",
|
|
"Cautery foot pedal intermittent contact",
|
|
]
|
|
# Deterministic asset mapping for 30 complaints:
|
|
# - assets[12]: 4 closed breakdowns in last 70d (repeat failure, red)
|
|
# - assets[14]: 3 closed breakdowns in last 60d (repeat failure)
|
|
# - assets[16]: 3 closed breakdowns in last 60d + expired contract (repeat failure + out-of-contract)
|
|
# - assets[2]: 1 closed breakdown + contract expiring in 3d (renewal review)
|
|
# - assets[18]: 2 closed breakdowns w/ high repair+spare cost (>45% of purchase_value)
|
|
# - assets[20]: 2 closed breakdowns w/ very high repair+spare cost (>100% of purchase_value)
|
|
# - assets[40]: fully depreciated asset w/ long downtime (efficiency < 80)
|
|
# - assets[0..9]: latest equipment with realistic breakdowns (including idx=26 critical open > 24h in ICU)
|
|
complaint_asset_indices = [
|
|
12, 12, 12, 12, # idx 0..3 (4 breakdowns on assets[12])
|
|
14, 14, 14, # idx 4..6 (3 breakdowns on assets[14])
|
|
16, 16, 16, # idx 7..9 (3 breakdowns on assets[16])
|
|
2, # idx 10 (contract expiring in 3d)
|
|
18, 18, # idx 11..12 (high maintenance cost > 40%)
|
|
20, 20, # idx 13..14 (high maintenance cost > 100%)
|
|
40, # idx 15 (fully depreciated w/ long downtime)
|
|
0, 1, 3, 4, 5, 7, # idx 16..21 (closed breakdowns on latest equipment)
|
|
6, 8, 9, 22, # idx 22..25 (in_progress)
|
|
2, # idx 26 (critical open > 24h in ICU, avoids assets[0])
|
|
10, 11, 13, # idx 27..29 (open)
|
|
]
|
|
repair_cost_indices = {0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 13, 14, 16, 18}
|
|
for idx in range(30):
|
|
asset = assets[complaint_asset_indices[idx]]
|
|
priority = "critical" if idx < 9 else "non_critical"
|
|
if idx < 22:
|
|
call_status = "closed"
|
|
elif idx < 26:
|
|
call_status = "in_progress"
|
|
else:
|
|
call_status = "open"
|
|
|
|
reg_user = dept_users[idx % len(dept_users)]
|
|
recv_user = bio_users[idx % len(bio_users)]
|
|
assigned_user = bio_users[(idx + 1) % len(bio_users)]
|
|
|
|
if idx == 26:
|
|
# Critical open > 24h (explicit requirement)
|
|
priority = "critical"
|
|
call_status = "open"
|
|
reg_at = now_utc - timedelta(hours=32)
|
|
closed_at = None
|
|
elif idx == 0:
|
|
# Spanning month boundary (registered last month, closed this month)
|
|
first_of_month = today.replace(day=1)
|
|
reg_date = first_of_month - timedelta(days=3)
|
|
close_date = first_of_month + timedelta(days=1) if first_of_month + timedelta(days=1) <= today else today
|
|
reg_at = _ist_to_utc(reg_date, 18, 30)
|
|
closed_at = _ist_to_utc(close_date, 11, 15)
|
|
elif idx == 15:
|
|
# Fully depreciated asset with extended downtime (to drop efficiency < 80)
|
|
reg_at = now_utc - timedelta(days=25, hours=4)
|
|
closed_at = reg_at + timedelta(days=12)
|
|
else:
|
|
days_back = rng.randint(5, 70) if call_status == "closed" else rng.randint(0, 3)
|
|
reg_at = now_utc - timedelta(days=days_back, hours=rng.randint(1, 10))
|
|
closed_at = reg_at + timedelta(hours=rng.randint(2, 24))
|
|
|
|
has_spare = idx in (1, 4, 8, 11, 13, 22)
|
|
has_ce = idx in (2, 6, 11, 18, 23)
|
|
|
|
c_assigned_at = reg_at + timedelta(minutes=25) if call_status in ("in_progress", "closed") else None
|
|
c_attended_at = (
|
|
reg_at + timedelta(hours=72) if idx == 15 else (reg_at + timedelta(minutes=65))
|
|
) if call_status in ("in_progress", "closed") else None
|
|
c_restored_at = (closed_at - timedelta(minutes=30)) if (call_status == "closed" and closed_at) else None
|
|
c_closed_at = closed_at if call_status == "closed" else None
|
|
|
|
if idx in (11, 12):
|
|
# assets[18] purchase_value ~ 450,000 -> push maintenance ratio ~55%
|
|
rep_cost = 115000.0
|
|
sp_cost = 45000.0 if has_spare else None
|
|
elif idx in (13, 14):
|
|
# assets[20] purchase_value ~ 950,000 -> push maintenance ratio > 105%
|
|
rep_cost = 520000.0
|
|
sp_cost = 140000.0 if has_spare else None
|
|
else:
|
|
rep_cost = float(rng.choice([3500, 6000, 9500, 12500, 18000])) if idx in repair_cost_indices else None
|
|
sp_cost = float(rng.choice([4500, 8200, 14500, 22000, 31500])) if has_spare else None
|
|
|
|
cov_at_reg = get_coverage(db, asset.id, reg_at.astimezone(KOLKATA).date())
|
|
|
|
comp = Complaint(
|
|
complaint_no=f"CMP-{today.year}-{idx + 1:04d}",
|
|
asset_id=asset.id,
|
|
description=issue_descriptions[idx % len(issue_descriptions)],
|
|
breakdown_details=f"Reported by {asset.department.code} nursing/technical staff during routine shift.",
|
|
priority=priority,
|
|
notes="Logged via XYZ AMS helpdesk.",
|
|
registered_at=reg_at,
|
|
registered_by_id=reg_user.id,
|
|
received_by_id=recv_user.id,
|
|
received_at=reg_at,
|
|
assigned_to_id=assigned_user.id if call_status in ("in_progress", "closed") else None,
|
|
assigned_at=c_assigned_at,
|
|
attended_by_id=assigned_user.id if call_status in ("in_progress", "closed") else None,
|
|
attended_at=c_attended_at,
|
|
restored_at=c_restored_at,
|
|
closed_by_id=assigned_user.id if call_status == "closed" else None,
|
|
closed_at=c_closed_at,
|
|
call_status=call_status,
|
|
closure_remarks="Equipment verified functional and handed back to department." if call_status == "closed" else None,
|
|
action_taken="Diagnosed faulty module, replaced worn harness, and ran safety check." if call_status in ("in_progress", "closed") else None,
|
|
root_cause="Component aging / power surge wear" if call_status == "closed" else None,
|
|
corrective_action="Module replacement and preventive recalibration" if call_status == "closed" else None,
|
|
lessons_learned="Verify UPS line conditioning during monthly rounds" if call_status == "closed" else None,
|
|
ce_name="Raghavendra Kulkarni (OEM Service)" if has_ce else None,
|
|
ce_attended_at=(reg_at + timedelta(hours=4)) if has_ce else None,
|
|
ce_action_taken="OEM service engineer inspected PCB assembly and updated firmware." if has_ce else None,
|
|
spare_required=has_spare,
|
|
spare_details="Power supply module / O2 sensor assembly" if has_spare else None,
|
|
spare_cost_estimate=sp_cost,
|
|
repair_cost=rep_cost,
|
|
coverage_tag=cov_at_reg["tag"],
|
|
coverage_contract_id=cov_at_reg["contract_id"],
|
|
coverage_provider_id=cov_at_reg["provider_id"],
|
|
updated_by_id=assigned_user.id,
|
|
)
|
|
db.add(comp)
|
|
db.flush()
|
|
complaints.append(comp)
|
|
|
|
db.add(
|
|
ComplaintEvent(
|
|
complaint_id=comp.id,
|
|
event_type="registered",
|
|
from_value=None,
|
|
to_value="open",
|
|
by_user_id=reg_user.id,
|
|
at=reg_at,
|
|
note="Complaint registered.",
|
|
)
|
|
)
|
|
if call_status in ("in_progress", "closed"):
|
|
db.add(
|
|
ComplaintEvent(
|
|
complaint_id=comp.id,
|
|
event_type="assigned",
|
|
from_value="open",
|
|
to_value="in_progress",
|
|
by_user_id=recv_user.id,
|
|
at=c_assigned_at,
|
|
note=f"Assigned to {assigned_user.name}.",
|
|
)
|
|
)
|
|
if call_status == "closed":
|
|
db.add(
|
|
ComplaintEvent(
|
|
complaint_id=comp.id,
|
|
event_type="closed",
|
|
from_value="in_progress",
|
|
to_value="closed",
|
|
by_user_id=assigned_user.id,
|
|
at=c_closed_at,
|
|
note="Restored and closed.",
|
|
)
|
|
)
|
|
db.flush()
|
|
|
|
# 15. Placeholder uploads (8 JPEGs + 6 PDFs) + Attachment records
|
|
target_upload_dir = upload_dir if upload_dir is not None else Path(settings.UPLOAD_DIR)
|
|
target_upload_dir.mkdir(parents=True, exist_ok=True)
|
|
# Remove previously seeded placeholder files (keep .gitkeep)
|
|
for existing_file in target_upload_dir.iterdir():
|
|
if existing_file.is_file() and existing_file.name != ".gitkeep":
|
|
existing_file.unlink()
|
|
|
|
palette = [
|
|
(30, 64, 175),
|
|
(15, 118, 110),
|
|
(180, 83, 9),
|
|
(109, 40, 217),
|
|
]
|
|
for j in range(8):
|
|
fname = f"seed_photo_{j + 1:02d}.jpg"
|
|
fpath = target_upload_dir / fname
|
|
size_b = _make_placeholder_jpeg(fpath, f"Equipment Fault Photo #{j + 1}", palette[j % len(palette)])
|
|
db.add(
|
|
Attachment(
|
|
entity_type="complaint",
|
|
entity_id=complaints[j].id,
|
|
original_name=f"fault_photo_{j + 1}.jpg",
|
|
stored_name=fname,
|
|
mime_type="image/jpeg",
|
|
size_bytes=size_b,
|
|
uploaded_by_id=bio_users[j % len(bio_users)].id,
|
|
)
|
|
)
|
|
|
|
for p in range(6):
|
|
fname = f"seed_doc_{p + 1:02d}.pdf"
|
|
fpath = target_upload_dir / fname
|
|
pdf_bytes = _make_minimal_pdf(f"XYZ Hospital Service / Calibration Report #{p + 1}")
|
|
fpath.write_bytes(pdf_bytes)
|
|
db.add(
|
|
Attachment(
|
|
entity_type="asset" if p < 3 else "complaint",
|
|
entity_id=assets[p].id if p < 3 else complaints[p + 8].id,
|
|
original_name=f"service_report_{p + 1}.pdf",
|
|
stored_name=fname,
|
|
mime_type="application/pdf",
|
|
size_bytes=len(pdf_bytes),
|
|
uploaded_by_id=coord_users[p % len(coord_users)].id,
|
|
)
|
|
)
|
|
db.flush()
|
|
|
|
# 16. Demo Equipment (3 items)
|
|
demo_items = [
|
|
("Portable Video Laryngoscope", "Airway Management", suppliers_and_oems[0].id, departments[0].id, locs_by_dept[departments[0].id][0].id, today - timedelta(days=10), today + timedelta(days=5), None, "Under clinical trial by ICU consultants."),
|
|
("High-Flow Nasal Cannula Unit", "Respiratory Support", suppliers_and_oems[1].id, departments[4].id, locs_by_dept[departments[4].id][0].id, today - timedelta(days=14), today + timedelta(days=2), None, "Evaluation unit due for vendor pickup shortly."),
|
|
("Point-of-Care Ultrasound Probe", "Diagnostic Imaging", suppliers_and_oems[2].id, departments[2].id, locs_by_dept[departments[2].id][2].id, today - timedelta(days=30), today - timedelta(days=5), today - timedelta(days=4), "Trial completed and returned to supplier."),
|
|
]
|
|
for name, eq_type, sup_id, dep_id, loc_id, s_d, exp_d, act_d, rem in demo_items:
|
|
db.add(
|
|
DemoEquipment(
|
|
name=name,
|
|
equipment_type=eq_type,
|
|
supplier_id=sup_id,
|
|
department_id=dep_id,
|
|
location_id=loc_id,
|
|
start_date=s_d,
|
|
expected_return_date=exp_d,
|
|
actual_return_date=act_d,
|
|
remarks=rem,
|
|
created_by_id=coord_users[0].id,
|
|
updated_by_id=coord_users[0].id,
|
|
)
|
|
)
|
|
db.flush()
|
|
|
|
# 17. Department Visits (12 total: 3 linked to complaints, 1 of which linked to 2 complaints)
|
|
for v_idx in range(12):
|
|
dept = departments[v_idx % len(departments)]
|
|
visit = DepartmentVisit(
|
|
department_id=dept.id,
|
|
visited_by_id=bio_users[v_idx % len(bio_users)].id,
|
|
visit_date=today - timedelta(days=v_idx * 4 + 1),
|
|
observations=f"Routine biomedical safety & preventive inspection round in {dept.name}.",
|
|
created_by_id=bio_users[v_idx % len(bio_users)].id,
|
|
updated_by_id=bio_users[v_idx % len(bio_users)].id,
|
|
)
|
|
dept_assets = [a for a in assets if a.department_id == dept.id][:2]
|
|
visit.assets.extend(dept_assets)
|
|
if v_idx == 0:
|
|
# 1 visit linked to 2 complaints
|
|
visit.complaints.extend([complaints[0], complaints[1]])
|
|
elif v_idx == 1:
|
|
visit.complaints.append(complaints[2])
|
|
elif v_idx == 2:
|
|
visit.complaints.append(complaints[3])
|
|
db.add(visit)
|
|
|
|
db.flush()
|
|
alert_res = run_alert_check(db)
|
|
db.commit()
|
|
return {
|
|
"departments": len(departments),
|
|
"locations": len(locations),
|
|
"categories": len(categories),
|
|
"vendors": len(vendors),
|
|
"users": len(users),
|
|
"assets": len(assets),
|
|
"contracts": len(contracts),
|
|
"warranties": 20,
|
|
"insurance_policies": len(insured_assets),
|
|
"calibration_plans": len(cal_assets),
|
|
"pm_schedules": 45,
|
|
"complaints": len(complaints),
|
|
"demo_equipment": len(demo_items),
|
|
"department_visits": 12,
|
|
"notifications": int(alert_res["created"]),
|
|
}
|
|
|
|
|
|
def main():
|
|
t0 = pytime.perf_counter()
|
|
Base.metadata.drop_all(bind=engine)
|
|
Base.metadata.create_all(bind=engine)
|
|
with SessionLocal() as db:
|
|
summary = seed_database(db)
|
|
elapsed = pytime.perf_counter() - t0
|
|
print(f"Seed completed in {elapsed:.2f}s: {summary}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|