File size: 23,268 Bytes
ef07288 | 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 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 | #!/usr/bin/env python3
"""
Seed Programme Chirurgical — Import structured cases into DB
Reads PROGRAM_CASES from data/seeds/programs.py, creates BlocCase +
TrackerCase entries in the database. Supports idempotent re-runs.
Usage:
PYTHONPATH=src python3 scripts/surgery/seed_programme.py
PYTHONPATH=src python3 scripts/surgery/seed_programme.py --dry-run
PYTHONPATH=src python3 scripts/surgery/seed_programme.py --report-only
Deduplication: patient_name + program_category + import_batch_id
"""
from __future__ import annotations
import asyncio
import os
import sys
from datetime import datetime, date
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional
from uuid import UUID, uuid4
# Ensure workspace root is on path
workspace = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(workspace / "src"))
sys.path.insert(0, str(workspace))
import structlog
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from apps.surgio.bloc.models import BlocCase
logger = structlog.get_logger(__name__)
# ═══════════════════════════════════════════════════════════
# DEFAULT TENANT — discovered from database or fallback
# ═══════════════════════════════════════════════════════════
BATCH_ID = "prog_chirurgie_2024_04"
async def discover_tenant(session: AsyncSession) -> tuple[UUID, UUID]:
"""Find the first tenant and user in the database, or create fallbacks."""
# Find tenant
result = await session.execute(text("SELECT id FROM tenants LIMIT 1"))
row = result.fetchone()
if row:
tenant_id = UUID(row[0]) if isinstance(row[0], str) else row[0]
else:
tenant_id = uuid4()
logger.warning("no_tenant_found", using_random=str(tenant_id))
# Find user
result = await session.execute(text("SELECT id FROM users LIMIT 1"))
row = result.fetchone()
if row:
user_id = UUID(row[0]) if isinstance(row[0], str) else row[0]
else:
user_id = uuid4()
logger.warning("no_user_found", using_random=str(user_id))
logger.info("tenant_discovered", tenant_id=str(tenant_id), user_id=str(user_id))
return tenant_id, user_id
# ═══════════════════════════════════════════════════════════
# SCHEMA MIGRATION — add missing columns if needed
# ═══════════════════════════════════════════════════════════
REQUIRED_COLUMNS = {
"surgeon": "VARCHAR(200)",
"site": "VARCHAR(100)",
"programme_category": "VARCHAR(30)",
"procedure_type": "VARCHAR(50)",
"equipment_requirements": "VARCHAR(500)",
"blood_requirements": "VARCHAR(200)",
"consent_status": "VARCHAR(14) DEFAULT 'missing'",
"logistics_flag": "VARCHAR(30) DEFAULT 'none'",
"cancellation_reason": "VARCHAR(500)",
"complications_30d": "JSON",
"readmission_30d": "BOOLEAN DEFAULT 0",
# Import tracking fields
"source_program": "VARCHAR(100)",
"raw_source_text": "TEXT",
"import_batch_id": "VARCHAR(50)",
"created_from_import": "BOOLEAN DEFAULT 0",
"review_required": "BOOLEAN DEFAULT 0",
"contact_status": "VARCHAR(30)",
"next_action": "VARCHAR(100)",
"operational_group": "VARCHAR(30)",
}
async def ensure_columns(session: AsyncSession) -> List[str]:
"""Add missing columns to bloc_cases table. Returns list of added columns."""
added = []
result = await session.execute(text("PRAGMA table_info(bloc_cases)"))
existing = {row[1] for row in result.fetchall()}
for col_name, col_type in REQUIRED_COLUMNS.items():
if col_name not in existing:
await session.execute(
text(f"ALTER TABLE bloc_cases ADD COLUMN {col_name} {col_type}")
)
added.append(col_name)
logger.info("column_added", table="bloc_cases", column=col_name)
if added:
await session.commit()
return added
# ═══════════════════════════════════════════════════════════
# DEDUPLICATION
# ═══════════════════════════════════════════════════════════
async def find_existing(
session: AsyncSession,
tenant_id: UUID,
patient_name: str,
program_category: Optional[str],
batch_id: str,
) -> Optional[BlocCase]:
"""Check if a case already exists (dedup by name + category + batch)."""
from sqlalchemy import select, and_
conditions = [
BlocCase.tenant_id == tenant_id,
BlocCase.patient_name == patient_name,
]
if program_category:
conditions.append(BlocCase.program_category == program_category)
conditions.append(BlocCase.import_batch_id == batch_id)
result = await session.execute(
select(BlocCase).where(and_(*conditions))
)
return result.scalar_one_or_none()
# ═══════════════════════════════════════════════════════════
# TRACES BRIDGE — create TrackerCase for each BlocCase
# ═══════════════════════════════════════════════════════════
async def create_trace_for_bloc(
session: AsyncSession,
tenant_id: UUID,
bloc: BlocCase,
) -> Optional[UUID]:
"""Create a TrackerCase linked to this BlocCase via raw SQL (table: traker_cases)."""
try:
from apps.traces.models import CaseState, CasePriority
# Map decision → state
state_map = {
"operate": "scheduled" if bloc.scheduled_date else "preparing",
"optimize": "preparing",
"observe": "preparing",
"transfer": "waiting",
"cancel": "cancelled",
"completed": "done",
}
# Map urgency → priority
priority_map = {
"urgent": "high",
"semi_urgent": "high",
"elective": "normal",
}
# Extract string value from decision/urgency (works with enum or plain str)
raw_decision = bloc.decision
decision_val = raw_decision.value if isinstance(raw_decision, Enum) else str(raw_decision)
raw_urgency = bloc.urgency
urgency_val = raw_urgency.value if isinstance(raw_urgency, Enum) else str(raw_urgency)
# Generate display ID
now = datetime.utcnow()
count_result = await session.execute(
text("SELECT COUNT(*) FROM traker_cases WHERE tenant_id = :tid"),
{"tid": str(tenant_id)},
)
count = count_result.scalar() or 0
display_id = f"TRK-{now.strftime('%Y%m%d')}-{count + 1:03d}"
# Blocking reason from missing items (handle plain strings from import)
blocking = None
try:
missing = []
bio = bloc.biology_status if isinstance(bloc.biology_status, str) else str(bloc.biology_status)
img = bloc.imaging_status if isinstance(bloc.imaging_status, str) else str(bloc.imaging_status)
anes = bloc.anesthesia_clearance if isinstance(bloc.anesthesia_clearance, str) else str(bloc.anesthesia_clearance)
consent = bloc.consent_status if isinstance(bloc.consent_status, str) else str(bloc.consent_status)
ok_values = ("ok", "not_applicable")
if bio not in ok_values:
missing.append(f"biology ({bio})")
if img not in ok_values:
missing.append(f"imaging ({img})")
if anes not in ok_values:
missing.append(f"anesthesia ({anes})")
if consent not in ok_values:
missing.append(f"consent ({consent})")
if missing:
blocking = "; ".join(missing[:3])
except Exception:
pass
trace_id = uuid4()
state = state_map.get(decision_val, "preparing")
priority = priority_map.get(urgency_val, "normal")
planned_action = bloc.planned_procedure or f"{decision_val}: {bloc.diagnosis}"
decision_date = str(bloc.scheduled_date) if bloc.scheduled_date else str(now.date())
action_date = str(bloc.scheduled_date) if bloc.scheduled_date else None
# Check readiness without calling model methods (which expect enum types)
ok_values = ("ok", "not_applicable")
bio = bloc.biology_status if isinstance(bloc.biology_status, str) else str(bloc.biology_status)
img = bloc.imaging_status if isinstance(bloc.imaging_status, str) else str(bloc.imaging_status)
anes = bloc.anesthesia_clearance if isinstance(bloc.anesthesia_clearance, str) else str(bloc.anesthesia_clearance)
consent_str = bloc.consent_status if isinstance(bloc.consent_status, str) else str(bloc.consent_status)
prep_ready = 1 if all(v in ok_values for v in (bio, img, anes, consent_str)) else 0
await session.execute(
text("""
INSERT INTO traker_cases (
id, display_id, tenant_id, subject_name, contact,
problem, planned_action, priority, state,
decision_date, action_date,
preparation_ready, safety_check,
blocking_reason, source_engine, source_ref,
is_deleted, created_at, updated_at
) VALUES (
:id, :display_id, :tenant_id, :subject_name, :contact,
:problem, :planned_action, :priority, :state,
:decision_date, :action_date,
:preparation_ready, :safety_check,
:blocking_reason, :source_engine, :source_ref,
:is_deleted, :created_at, :updated_at
)
"""),
{
"id": str(trace_id),
"display_id": display_id,
"tenant_id": str(tenant_id),
"subject_name": bloc.patient_name,
"contact": bloc.phone,
"problem": bloc.diagnosis,
"planned_action": planned_action[:500],
"priority": priority,
"state": state,
"decision_date": decision_date,
"action_date": action_date,
"preparation_ready": prep_ready,
"safety_check": 0,
"blocking_reason": blocking,
"source_engine": "surgio",
"source_ref": str(bloc.id),
"is_deleted": 0,
"created_at": now.isoformat(),
"updated_at": now.isoformat(),
},
)
return trace_id
except Exception as e:
logger.warning("trace_creation_skipped", error=str(e), patient=bloc.patient_name)
return None
# ═══════════════════════════════════════════════════════════
# MAIN IMPORT
# ═══════════════════════════════════════════════════════════
async def seed_programme(
database_url: str,
dry_run: bool = False,
report_only: bool = False,
) -> Dict[str, Any]:
"""
Import programme chirurgical into database.
Returns import report dict.
"""
from data.seeds.programs import PROGRAM_CASES, _IMPORT_META
engine = create_async_engine(database_url, echo=False)
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
report = {
"total_parsed": len(PROGRAM_CASES),
"imported": 0,
"skipped_duplicate": 0,
"skipped_error": 0,
"traces_created": 0,
"columns_added": [],
"by_group": {},
"by_category": {},
"by_decision": {},
"missing_phone": [],
"missing_asa": [],
"uncertain_diagnosis": [],
"review_required": [],
"errors": [],
}
async with async_session() as session:
# Step 0: Discover tenant and user
tenant_id, user_id = await discover_tenant(session)
# Step 1: Ensure schema has all columns
added_cols = await ensure_columns(session)
report["columns_added"] = added_cols
if report_only:
# Just classify and report without inserting
for case_data in PROGRAM_CASES:
_classify_for_report(case_data, report)
await engine.dispose()
return report
# Step 2: Import each case
for idx, case_data in enumerate(PROGRAM_CASES):
try:
# Merge import metadata
merged = {**_IMPORT_META, **case_data}
patient_name = merged["patient_name"]
program_category = merged.get("program_category")
batch_id = merged.get("import_batch_id", BATCH_ID)
# Classify for report
_classify_for_report(merged, report)
if dry_run:
report["imported"] += 1
continue
# Dedup check
existing = await find_existing(
session, tenant_id, patient_name, program_category, batch_id
)
if existing:
report["skipped_duplicate"] += 1
logger.info("case_skipped_duplicate", patient=patient_name)
continue
# Build BlocCase
bloc = _build_bloc_case(merged, tenant_id, user_id)
session.add(bloc)
await session.flush()
# Create Traces entry
trace_id = await create_trace_for_bloc(session, tenant_id, bloc)
if trace_id:
report["traces_created"] += 1
report["imported"] += 1
logger.info(
"case_imported",
patient=patient_name,
group=merged.get("operational_group"),
decision=merged.get("decision"),
)
except Exception as e:
report["skipped_error"] += 1
report["errors"].append({"index": idx, "error": str(e)})
logger.error("case_import_error", index=idx, error=str(e))
if not dry_run:
await session.commit()
await engine.dispose()
return report
def _build_bloc_case(data: Dict[str, Any], tenant_id: UUID, user_id: UUID) -> BlocCase:
"""Build a BlocCase from merged case data dict."""
now = datetime.utcnow()
# Handle date fields
scheduled_date = data.get("scheduled_date")
if isinstance(scheduled_date, str):
try:
scheduled_date = date.fromisoformat(scheduled_date)
except ValueError:
scheduled_date = None
# Handle evidence: strip result_date strings → date objects
evidence = []
for e in data.get("evidence", []):
ev = dict(e)
if "result_date" in ev and isinstance(ev["result_date"], str):
ev["result_date"] = ev["result_date"] # Keep as string in JSON
evidence.append(ev)
return BlocCase(
id=uuid4(),
tenant_id=tenant_id,
created_by=user_id,
updated_by=user_id,
created_at=now,
updated_at=now,
# Identity
patient_name=data["patient_name"],
phone=data.get("phone"),
surgeon=data.get("surgeon"),
site=data.get("site"),
administrative_status=data.get("administrative_status", "free"),
# Classification
program_category=data.get("program_category"),
procedure_type=data.get("procedure_type"),
# Clinical
diagnosis=data["diagnosis"],
asa_score=data.get("asa_score"),
urgency=data.get("urgency", "elective"),
risk_level=data.get("risk_level", "low"),
comorbidities=data.get("comorbidities", []),
# Evidence
evidence=evidence,
certainty_level=data.get("certainty_level", "uncertain"),
# Readiness
biology_status=data.get("biology_status", "missing"),
imaging_status=data.get("imaging_status", "missing"),
anesthesia_clearance=data.get("anesthesia_clearance", "missing"),
consent_status=data.get("consent_status", "missing"),
optimization_status=data.get("optimization_status", "none"),
# Decision
decision=data.get("decision", "observe"),
decision_reason=data.get("decision_reason"),
decision_at=now,
decision_by=user_id,
# Surgical plan
planned_procedure=data.get("planned_procedure"),
technique=data.get("technique"),
scheduled_date=scheduled_date,
estimated_duration_min=data.get("estimated_duration_min"),
# Logistics
logistics_flag=data.get("logistics_flag", "none"),
logistic_constraints=data.get("logistic_constraints"),
postop_destination=data.get("postop_destination", "ward"),
# Import tracking
source_program=data.get("source_program"),
raw_source_text=data.get("raw_source_text"),
import_batch_id=data.get("import_batch_id", BATCH_ID),
created_from_import=data.get("created_from_import", True),
review_required=data.get("review_required", False),
contact_status=data.get("contact_status"),
next_action=data.get("next_action"),
operational_group=data.get("operational_group"),
)
def _classify_for_report(data: Dict[str, Any], report: Dict[str, Any]):
"""Classify a case for the import report."""
group = data.get("operational_group", "needs_review")
category = data.get("program_category", "other")
decision = data.get("decision", "observe")
report["by_group"][group] = report["by_group"].get(group, 0) + 1
report["by_category"][category] = report["by_category"].get(category, 0) + 1
report["by_decision"][decision] = report["by_decision"].get(decision, 0) + 1
if not data.get("phone"):
report["missing_phone"].append(data["patient_name"])
if not data.get("asa_score"):
report["missing_asa"].append(data["patient_name"])
if data.get("certainty_level") == "uncertain":
report["uncertain_diagnosis"].append(data["patient_name"])
if data.get("review_required"):
report["review_required"].append(data["patient_name"])
def print_report(report: Dict[str, Any]):
"""Print a human-readable import report."""
print("\n" + "=" * 70)
print(" PROGRAMME CHIRURGICAL — IMPORT REPORT")
print("=" * 70)
print(f"\n📊 IMPORT SUMMARY")
print(f" Total cases parsed: {report['total_parsed']}")
print(f" Successfully imported: {report['imported']}")
print(f" Skipped (duplicate): {report['skipped_duplicate']}")
print(f" Skipped (error): {report['skipped_error']}")
print(f" Traces created: {report['traces_created']}")
if report["columns_added"]:
print(f"\n🔧 SCHEMA UPDATES")
print(f" Columns added: {', '.join(report['columns_added'])}")
print(f"\n📋 BY OPERATIONAL GROUP")
for group, count in sorted(report["by_group"].items()):
icon = {
"ready_for_bloc": "✅",
"optimize_before_bloc": "⚡",
"awaiting_evidence": "🔍",
"logistics_special": "🚛",
"fast_track_minor": "⚡",
"needs_review": "👁️",
"external": "🔗",
}.get(group, "📌")
print(f" {icon} {group:.<30} {count}")
print(f"\n📂 BY CATEGORY")
for cat, count in sorted(report["by_category"].items()):
print(f" {cat:.<30} {count}")
print(f"\n🎯 BY DECISION")
for dec, count in sorted(report["by_decision"].items()):
print(f" {dec:.<30} {count}")
print(f"\n⚠️ DATA QUALITY")
print(f" Missing phone: {len(report['missing_phone'])}")
if report["missing_phone"]:
for name in report["missing_phone"]:
print(f" → {name}")
print(f" Missing ASA: {len(report['missing_asa'])}")
if report["missing_asa"]:
for name in report["missing_asa"]:
print(f" → {name}")
print(f" Uncertain diagnosis: {len(report['uncertain_diagnosis'])}")
if report["uncertain_diagnosis"]:
for name in report["uncertain_diagnosis"]:
print(f" → {name}")
print(f" Review required: {len(report['review_required'])}")
if report["review_required"]:
for name in report["review_required"]:
print(f" → {name}")
if report["errors"]:
print(f"\n❌ ERRORS")
for err in report["errors"]:
print(f" Case #{err['index']}: {err['error']}")
print("\n" + "=" * 70)
# ═══════════════════════════════════════════════════════════
# CLI
# ═══════════════════════════════════════════════════════════
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Seed programme chirurgical into database")
parser.add_argument("--dry-run", action="store_true", help="Parse and validate without inserting")
parser.add_argument("--report-only", action="store_true", help="Only generate classification report")
parser.add_argument("--db-url", default=None, help="Database URL override")
args = parser.parse_args()
db_url = args.db_url or os.getenv(
"DATABASE_URL",
"sqlite+aiosqlite:///./data/databases/yaz_care.db",
)
# Ensure aiosqlite for SQLite
if db_url.startswith("sqlite://") and "aiosqlite" not in db_url:
db_url = db_url.replace("sqlite://", "sqlite+aiosqlite://")
report = asyncio.run(
seed_programme(
database_url=db_url,
dry_run=args.dry_run,
report_only=args.report_only,
)
)
print_report(report)
if args.dry_run:
print("\n🔸 DRY RUN — no data was inserted. Run without --dry-run to import.")
elif args.report_only:
print("\n🔸 REPORT ONLY — no data was inserted.")
else:
print("\n✅ Programme imported successfully. Open SURGIO to start working on cases.")
|