File size: 16,222 Bytes
372384b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | #!/usr/bin/env python3
"""
YAZ Care Platform - Database Seeder
Seed database with sample data for development and testing
"""
import argparse
import asyncio
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
class DatabaseSeeder:
"""Seed database with sample data"""
def __init__(self, environment: str = "development"):
self.environment = environment
self.seeded_data: Dict[str, List[Any]] = {}
async def seed_all(self):
"""Seed all data"""
print(f"\n🌱 Seeding database for: {self.environment}")
print(f"⏰ Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
try:
# Seed in dependency order
await self.seed_tenants()
await self.seed_users()
await self.seed_patients()
await self.seed_providers()
await self.seed_encounters()
await self.seed_surgeries()
await self.seed_lab_orders()
await self.seed_prescriptions()
print(f"\n✅ Database seeding completed successfully!")
self._print_summary()
except Exception as e:
print(f"\n❌ Seeding failed: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
async def seed_tenants(self):
"""Seed tenant data"""
print("📊 Seeding tenants...")
tenants = [
{
"id": str(uuid4()),
"name": "General Hospital",
"subdomain": "general",
"settings": {
"timezone": "America/New_York",
"locale": "en-US"
},
"is_active": True
},
{
"id": str(uuid4()),
"name": "Children's Medical Center",
"subdomain": "children",
"settings": {
"timezone": "America/Los_Angeles",
"locale": "en-US"
},
"is_active": True
},
{
"id": str(uuid4()),
"name": "University Hospital",
"subdomain": "university",
"settings": {
"timezone": "America/Chicago",
"locale": "en-US"
},
"is_active": True
}
]
self.seeded_data["tenants"] = tenants
print(f" ✓ Created {len(tenants)} tenants")
async def seed_users(self):
"""Seed user data"""
print("👥 Seeding users...")
users = []
roles = ["admin", "doctor", "nurse", "lab_tech", "pharmacist"]
for i, tenant in enumerate(self.seeded_data["tenants"]):
for role in roles:
user = {
"id": str(uuid4()),
"username": f"{role}{i+1}",
"email": f"{role}{i+1}@{tenant['subdomain']}.com",
"full_name": f"{role.title()} User {i+1}",
"role": role,
"tenant_id": tenant["id"],
"is_active": True
}
users.append(user)
self.seeded_data["users"] = users
print(f" ✓ Created {len(users)} users")
async def seed_patients(self):
"""Seed patient data"""
print("🏥 Seeding patients...")
first_names = ["John", "Mary", "Michael", "Sarah", "David", "Emily", "James", "Jennifer", "Robert", "Linda"]
last_names = ["Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller", "Davis", "Rodriguez", "Martinez"]
patients = []
for tenant in self.seeded_data["tenants"]:
for i in range(50): # 50 patients per tenant
patient = {
"id": str(uuid4()),
"medical_record_number": f"MRN{tenant['subdomain'][:3].upper()}{i+1:05d}",
"first_name": first_names[i % len(first_names)],
"last_name": last_names[i % len(last_names)],
"date_of_birth": (datetime.now() - timedelta(days=365 * (20 + i % 60))).date().isoformat(),
"gender": ["male", "female"][i % 2],
"email": f"patient{i+1}@example.com",
"phone": f"+1-555-{i:04d}",
"tenant_id": tenant["id"],
"created_at": datetime.now().isoformat()
}
patients.append(patient)
self.seeded_data["patients"] = patients
print(f" ✓ Created {len(patients)} patients")
async def seed_providers(self):
"""Seed provider/practitioner data"""
print("👨⚕️ Seeding providers...")
specialties = [
"Internal Medicine",
"General Surgery",
"Pediatrics",
"Cardiology",
"Orthopedics",
"Anesthesiology",
"Emergency Medicine",
"Family Medicine"
]
providers = []
for tenant in self.seeded_data["tenants"]:
for i, specialty in enumerate(specialties):
provider = {
"id": str(uuid4()),
"npi": f"1{tenant['subdomain'][:3].upper()}{i+1:06d}",
"first_name": f"Dr. {['James', 'Sarah', 'Michael', 'Emily'][i % 4]}",
"last_name": f"{['Smith', 'Johnson', 'Williams', 'Brown'][i % 4]}",
"specialty": specialty,
"tenant_id": tenant["id"],
"is_active": True
}
providers.append(provider)
self.seeded_data["providers"] = providers
print(f" ✓ Created {len(providers)} providers")
async def seed_encounters(self):
"""Seed encounter data"""
print("📋 Seeding encounters...")
encounter_types = ["outpatient", "inpatient", "emergency", "virtual"]
encounters = []
for tenant in self.seeded_data["tenants"]:
tenant_patients = [p for p in self.seeded_data["patients"] if p["tenant_id"] == tenant["id"]]
tenant_providers = [p for p in self.seeded_data["providers"] if p["tenant_id"] == tenant["id"]]
for i in range(100): # 100 encounters per tenant
patient = tenant_patients[i % len(tenant_patients)]
provider = tenant_providers[i % len(tenant_providers)]
encounter_date = datetime.now() - timedelta(days=i)
encounter = {
"id": str(uuid4()),
"patient_id": patient["id"],
"provider_id": provider["id"],
"encounter_type": encounter_types[i % len(encounter_types)],
"scheduled_date": encounter_date.isoformat(),
"status": ["scheduled", "in-progress", "completed"][i % 3],
"chief_complaint": [
"Annual physical",
"Follow-up visit",
"New patient consultation",
"Routine checkup"
][i % 4],
"tenant_id": tenant["id"],
"created_at": encounter_date.isoformat()
}
encounters.append(encounter)
self.seeded_data["encounters"] = encounters
print(f" ✓ Created {len(encounters)} encounters")
async def seed_surgeries(self):
"""Seed surgical procedure data"""
print("🔪 Seeding surgeries...")
procedures = [
("47562", "Laparoscopic cholecystectomy"),
("27447", "Total knee arthroplasty"),
("27130", "Total hip arthroplasty"),
("43280", "Laparoscopic fundoplication"),
("49505", "Inguinal hernia repair")
]
surgeries = []
for tenant in self.seeded_data["tenants"]:
tenant_patients = [p for p in self.seeded_data["patients"] if p["tenant_id"] == tenant["id"]]
tenant_providers = [p for p in self.seeded_data["providers"]
if p["tenant_id"] == tenant["id"] and "Surgery" in p.get("specialty", "")]
if not tenant_providers:
continue
for i in range(20): # 20 surgeries per tenant
patient = tenant_patients[i % len(tenant_patients)]
provider = tenant_providers[i % len(tenant_providers)]
procedure = procedures[i % len(procedures)]
surgery_date = datetime.now() + timedelta(days=i+1)
surgery = {
"id": str(uuid4()),
"patient_id": patient["id"],
"surgeon_id": provider["id"],
"procedure_code": procedure[0],
"procedure_name": procedure[1],
"scheduled_date": surgery_date.isoformat(),
"estimated_duration_minutes": 90 + (i * 30) % 180,
"operating_room": f"OR-{(i % 5) + 1}",
"status": "scheduled",
"priority": ["elective", "urgent"][i % 2],
"tenant_id": tenant["id"],
"created_at": datetime.now().isoformat()
}
surgeries.append(surgery)
self.seeded_data["surgeries"] = surgeries
print(f" ✓ Created {len(surgeries)} surgeries")
async def seed_lab_orders(self):
"""Seed laboratory order data"""
print("🧪 Seeding lab orders...")
test_panels = [
("CBC", "Complete Blood Count"),
("CMP", "Comprehensive Metabolic Panel"),
("LIPID", "Lipid Panel"),
("HBA1C", "Hemoglobin A1C"),
("TSH", "Thyroid Stimulating Hormone")
]
lab_orders = []
for tenant in self.seeded_data["tenants"]:
tenant_encounters = [e for e in self.seeded_data["encounters"] if e["tenant_id"] == tenant["id"]]
for i in range(50): # 50 lab orders per tenant
encounter = tenant_encounters[i % len(tenant_encounters)]
test = test_panels[i % len(test_panels)]
order = {
"id": str(uuid4()),
"patient_id": encounter["patient_id"],
"encounter_id": encounter["id"],
"test_code": test[0],
"test_name": test[1],
"status": ["ordered", "collected", "processing", "completed"][i % 4],
"priority": ["routine", "urgent", "stat"][i % 3],
"tenant_id": tenant["id"],
"created_at": datetime.now().isoformat()
}
lab_orders.append(order)
self.seeded_data["lab_orders"] = lab_orders
print(f" ✓ Created {len(lab_orders)} lab orders")
async def seed_prescriptions(self):
"""Seed prescription data"""
print("💊 Seeding prescriptions...")
medications = [
("Lisinopril", "10mg", "tablet"),
("Metformin", "500mg", "tablet"),
("Atorvastatin", "20mg", "tablet"),
("Omeprazole", "20mg", "capsule"),
("Levothyroxine", "50mcg", "tablet")
]
prescriptions = []
for tenant in self.seeded_data["tenants"]:
tenant_encounters = [e for e in self.seeded_data["encounters"]
if e["tenant_id"] == tenant["id"] and e["status"] == "completed"]
for i in range(30): # 30 prescriptions per tenant
if not tenant_encounters:
break
encounter = tenant_encounters[i % len(tenant_encounters)]
medication = medications[i % len(medications)]
prescription = {
"id": str(uuid4()),
"patient_id": encounter["patient_id"],
"encounter_id": encounter["id"],
"prescriber_id": encounter["provider_id"],
"medication_name": medication[0],
"dosage": medication[1],
"form": medication[2],
"route": "oral",
"frequency": "once daily",
"duration_days": 90,
"quantity": 90,
"refills": 3,
"status": "active",
"tenant_id": tenant["id"],
"created_at": datetime.now().isoformat()
}
prescriptions.append(prescription)
self.seeded_data["prescriptions"] = prescriptions
print(f" ✓ Created {len(prescriptions)} prescriptions")
def _print_summary(self):
"""Print seeding summary"""
print(f"\n📊 Seeding Summary:")
print(f"{'='*50}")
for category, items in self.seeded_data.items():
print(f" {category.title():20s}: {len(items):5d} records")
total = sum(len(items) for items in self.seeded_data.values())
print(f"{'='*50}")
print(f" {'Total':20s}: {total:5d} records")
print(f"\n⏰ Completed at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
async def export_seed_data(self, output_file: str):
"""Export seed data to JSON file"""
import json
output_path = Path(output_file)
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, 'w') as f:
json.dump(self.seeded_data, f, indent=2)
print(f"\n💾 Seed data exported to: {output_path}")
def main():
"""Main CLI entry point"""
parser = argparse.ArgumentParser(
description="YAZ Care Platform - Database Seeder",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Seed development database
python seed_database.py
# Seed with specific environment
python seed_database.py --environment staging
# Export seed data to file
python seed_database.py --export data/seeds/sample_data.json
# Clear database before seeding
python seed_database.py --clear
"""
)
parser.add_argument(
"--environment",
default="development",
choices=["development", "staging", "testing"],
help="Target environment"
)
parser.add_argument(
"--export",
help="Export seed data to JSON file"
)
parser.add_argument(
"--clear",
action="store_true",
help="Clear existing data before seeding"
)
parser.add_argument(
"--tenants-only",
action="store_true",
help="Seed only tenant data"
)
parser.add_argument(
"--users-only",
action="store_true",
help="Seed only user data"
)
args = parser.parse_args()
if args.clear:
response = input("⚠️ This will clear existing data. Continue? (y/N): ")
if response.lower() != 'y':
print("❌ Seeding cancelled")
return
seeder = DatabaseSeeder(environment=args.environment)
try:
asyncio.run(seeder.seed_all())
if args.export:
asyncio.run(seeder.export_seed_data(args.export))
except KeyboardInterrupt:
print("\n\n❌ Seeding interrupted by user")
sys.exit(1)
except Exception as e:
print(f"\n❌ Seeding failed: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()
|