""" Educa (Medical Education) Domain Models Clinical Context: Medical education tracking, competency assessment, duty hours monitoring, ACGME compliance, milestone tracking. Standards Compliance: - ACGME (Accreditation Council for Graduate Medical Education) - ACGME duty hour requirements (80-hour work week) - ACGME milestones and competencies - Liaison Committee on Medical Education (LCME) standards Performance: <100ms query time for duty hour calculations """ from datetime import datetime, date, time from typing import Optional, List, Dict, Any from enum import Enum from sqlmodel import SQLModel, Field, Relationship, Column from sqlalchemy import JSON from pydantic import field_validator from core.database.mixins import TenantMixin, TimestampMixin class LearnerType(str, Enum): """Type of medical learner""" MEDICAL_STUDENT = "medical_student" RESIDENT = "resident" FELLOW = "fellow" NURSE_PRACTITIONER_STUDENT = "np_student" PA_STUDENT = "pa_student" PHARMACY_STUDENT = "pharmacy_student" # Alias for backward compatibility LearnerLevel = LearnerType class ProgramType(str, Enum): """Type of training program""" MD = "doctor_of_medicine" DO = "doctor_of_osteopathy" RESIDENCY = "residency" FELLOWSHIP = "fellowship" NP = "nurse_practitioner" PA = "physician_assistant" PHARMACY = "pharmacy" class RotationType(str, Enum): """Type of clinical rotation""" CORE = "core" ELECTIVE = "elective" REQUIRED = "required" RESEARCH = "research" VACATION = "vacation" class RotationStatus(str, Enum): """Status of clinical rotation""" SCHEDULED = "scheduled" ACTIVE = "active" COMPLETED = "completed" CANCELLED = "cancelled" class CompetencyDomain(str, Enum): """ACGME competency domains""" PATIENT_CARE = "patient_care" MEDICAL_KNOWLEDGE = "medical_knowledge" PRACTICE_BASED_LEARNING = "practice_based_learning" INTERPERSONAL_SKILLS = "interpersonal_skills" PROFESSIONALISM = "professionalism" SYSTEMS_BASED_PRACTICE = "systems_based_practice" class MilestoneLevel(str, Enum): """ACGME milestone levels""" LEVEL_1 = "level_1" LEVEL_2 = "level_2" LEVEL_3 = "level_3" LEVEL_4 = "level_4" LEVEL_5 = "level_5" class CaseLogCategory(str, Enum): """Categories for case logging""" SURGICAL = "surgical" MEDICAL = "medical" PROCEDURAL = "procedural" DIAGNOSTIC = "diagnostic" CONSULTATION = "consultation" class CompetencyLevel(str, Enum): """ACGME milestone competency levels""" LEVEL_1 = "level_1_novice" LEVEL_2 = "level_2_advanced_beginner" LEVEL_3 = "level_3_competent" LEVEL_4 = "level_4_proficient" LEVEL_5 = "level_5_expert" class AssessmentType(str, Enum): """Type of educational assessment""" FORMATIVE = "formative" SUMMATIVE = "summative" MILESTONE = "milestone" OSCE = "osce" EXAM = "written_exam" PROCEDURAL = "procedural" SIMULATION = "simulation" # ============================================================================ # Learners and Programs # ============================================================================ class Learner(TenantMixin, TimestampMixin, SQLModel, table=True): """ Medical learner (student, resident, fellow). Clinical Context: Tracks educational progress, competency development ACGME: Core component for program compliance HIPAA: Limited PHI - educational records """ __tablename__ = "learners" __table_args__ = {"schema": "educa", "extend_existing": True} id: str = Field(primary_key=True) # Identification learner_id: str = Field(max_length=100, unique=True, index=True) user_id: Optional[str] = Field(default=None) # Link to auth system # Personal information first_name: str = Field(max_length=100) last_name: str = Field(max_length=100) email: str = Field(max_length=255, unique=True) # Program information learner_type: LearnerType program_id: str = Field(foreign_key="educa.training_programs.id", index=True) year_of_training: int = Field(ge=1, le=10) # PGY-1, PGY-2, etc. # Dates matriculation_date: date expected_graduation_date: date actual_graduation_date: Optional[date] = None # Status is_active: bool = Field(default=True, index=True) on_leave: bool = Field(default=False) leave_start_date: Optional[date] = None leave_end_date: Optional[date] = None # Relationships program: Optional["TrainingProgram"] = Relationship(back_populates="learners") rotations: List["Rotation"] = Relationship(back_populates="learner") duty_hours: List["DutyHourLog"] = Relationship(back_populates="learner") assessments: List["Assessment"] = Relationship(back_populates="learner") competencies: List["CompetencyRecord"] = Relationship(back_populates="learner") class TrainingProgram(TenantMixin, TimestampMixin, SQLModel, table=True): """ Medical training program (residency, fellowship, etc.). Clinical Context: ACGME-accredited training programs Compliance: Must track all ACGME requirements """ __tablename__ = "training_programs" __table_args__ = {"schema": "educa", "extend_existing": True} id: str = Field(primary_key=True) # Program identification program_name: str = Field(max_length=255) program_type: ProgramType specialty: str = Field(max_length=200) # Accreditation acgme_program_number: Optional[str] = Field(default=None, max_length=100) accreditation_status: str = Field(max_length=100) next_accreditation_review: Optional[date] = None # Program details program_director_id: str coordinator_id: Optional[str] = None duration_years: int = Field(ge=1, le=10) # Capacity total_positions: int current_enrollment: int = Field(default=0) # Status is_active: bool = Field(default=True) # Relationships learners: List["Learner"] = Relationship(back_populates="program") rotations: List["Rotation"] = Relationship(back_populates="program") # ============================================================================ # Rotations and Schedules # ============================================================================ class Rotation(TenantMixin, TimestampMixin, SQLModel, table=True): """ Clinical rotation assignment. Clinical Context: Tracks learner rotations through clinical services ACGME: Required documentation for program compliance """ __tablename__ = "rotations" __table_args__ = {"schema": "educa", "extend_existing": True} id: str = Field(primary_key=True) # Learner and program learner_id: str = Field(foreign_key="educa.learners.id", index=True) program_id: str = Field(foreign_key="educa.training_programs.id", index=True) # Rotation details rotation_name: str = Field(max_length=255) rotation_type: RotationType service: str = Field(max_length=200) # Internal Medicine, Surgery, etc. department: str = Field(max_length=200) site: str = Field(max_length=200) # Hospital or clinic name # Dates start_date: date = Field(index=True) end_date: date # Supervision attending_physician_id: str senior_resident_id: Optional[str] = None # Goals and objectives learning_objectives: Optional[str] = None rotation_goals: Optional[str] = None # Completion is_completed: bool = Field(default=False) completion_date: Optional[date] = None final_evaluation_completed: bool = Field(default=False) # Lifecycle (core.lifecycle module) pre_session_prep: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) session_events: List[Dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) completion_plan: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) # Relationships learner: Optional["Learner"] = Relationship(back_populates="rotations") program: Optional["TrainingProgram"] = Relationship(back_populates="rotations") # ============================================================================ # Duty Hours (ACGME Compliance) # ============================================================================ class DutyHourLog(TenantMixin, TimestampMixin, SQLModel, table=True): """ Duty hour logging for ACGME compliance. Clinical Context: ACGME requires 80-hour work week limit, mandatory rest periods Compliance: CRITICAL for program accreditation Performance: Real-time duty hour tracking with automated alerts ACGME Requirements: - 80 hours per week (averaged over 4 weeks) - 1 day off per week (averaged over 4 weeks) - 10 hours rest between shifts - 24 hours continuous duty + 4 hours for transitions """ __tablename__ = "duty_hour_logs" __table_args__ = {"schema": "educa", "extend_existing": True} id: str = Field(primary_key=True) learner_id: str = Field(foreign_key="educa.learners.id", index=True) rotation_id: Optional[str] = Field(default=None, foreign_key="educa.rotations.id", index=True) # Shift details shift_date: date = Field(index=True) shift_start: datetime shift_end: datetime # Calculated fields hours_worked: float = Field(ge=0.0, le=48.0) # Max 24+4 hours per ACGME is_call_shift: bool = Field(default=False) is_home_call: bool = Field(default=False) # Rest period compliance hours_since_last_shift: Optional[float] = None rest_period_compliant: bool = Field(default=True) # >10 hours required # Notes activities: Optional[str] = None violations_noted: Optional[str] = None # Approval is_approved: bool = Field(default=False) approved_by: Optional[str] = None approved_at: Optional[datetime] = None # Relationships learner: Optional["Learner"] = Relationship(back_populates="duty_hours") @field_validator("hours_worked", mode="before") @classmethod def calculate_hours(cls, v, info): """Calculate hours worked from shift times""" values = info.data if "shift_start" in values and "shift_end" in values: start = values["shift_start"] end = values["shift_end"] if start and end: duration = (end - start).total_seconds() / 3600.0 return round(duration, 2) return v class DutyHourSummary(TenantMixin, TimestampMixin, SQLModel, table=True): """ Weekly summary of duty hours for compliance reporting. Clinical Context: Aggregated view for program directors and compliance officers ACGME: Weekly monitoring of 80-hour limit """ __tablename__ = "duty_hour_summaries" __table_args__ = {"schema": "educa", "extend_existing": True} id: str = Field(primary_key=True) learner_id: str = Field(foreign_key="educa.learners.id", index=True) # Week identification week_start_date: date = Field(index=True) week_end_date: date year: int week_number: int # Hour totals total_hours: float = Field(ge=0.0) clinical_hours: float = Field(ge=0.0) call_hours: float = Field(ge=0.0) home_call_hours: float = Field(ge=0.0) # Compliance is_compliant: bool = Field(default=True) hours_over_limit: float = Field(default=0.0) days_off_count: int = Field(ge=0, le=7) rest_violations_count: int = Field(default=0) # 4-week rolling average (ACGME requirement) four_week_avg_hours: Optional[float] = None four_week_compliant: bool = Field(default=True) # ============================================================================ # Competency Assessment # ============================================================================ class CompetencyRecord(TenantMixin, TimestampMixin, SQLModel, table=True): """ ACGME competency and milestone tracking. Clinical Context: Documents learner progress through milestones ACGME: Six core competencies required Six Core Competencies: 1. Patient Care 2. Medical Knowledge 3. Practice-Based Learning and Improvement 4. Interpersonal and Communication Skills 5. Professionalism 6. Systems-Based Practice """ __tablename__ = "competency_records" __table_args__ = {"schema": "educa", "extend_existing": True} id: str = Field(primary_key=True) learner_id: str = Field(foreign_key="educa.learners.id", index=True) rotation_id: Optional[str] = Field(default=None, foreign_key="educa.rotations.id", index=True) # Competency identification competency_domain: str = Field(max_length=200) # One of six core competencies milestone_number: str = Field(max_length=50) milestone_description: str # Assessment competency_level: CompetencyLevel assessment_date: date = Field(index=True) assessor_id: str # Faculty member # Evidence evidence_description: Optional[str] = None case_ids: Optional[List[str]] = Field(default=None, sa_column=Column(JSON)) # Comments strengths: Optional[str] = None areas_for_improvement: Optional[str] = None action_plan: Optional[str] = None # Relationships learner: Optional["Learner"] = Relationship(back_populates="competencies") class Assessment(TenantMixin, TimestampMixin, SQLModel, table=True): """ Educational assessment (formative, summative, milestone). Clinical Context: 360-degree evaluations, OSCEs, written exams """ __tablename__ = "assessments" __table_args__ = {"schema": "educa", "extend_existing": True} id: str = Field(primary_key=True) learner_id: str = Field(foreign_key="educa.learners.id", index=True) rotation_id: Optional[str] = Field(default=None, foreign_key="educa.rotations.id", index=True) # Assessment details assessment_type: AssessmentType assessment_name: str = Field(max_length=255) assessment_date: date = Field(index=True) # Assessor assessor_id: str assessor_role: str = Field(max_length=100) # Attending, Peer, Nurse, Patient # Scoring score: Optional[float] = None max_score: Optional[float] = None pass_fail: Optional[str] = Field(default=None, max_length=50) # Feedback narrative_feedback: Optional[str] = None strengths: Optional[str] = None areas_for_improvement: Optional[str] = None # Structured ratings (JSON for flexibility) rating_scores: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # Status is_completed: bool = Field(default=True) learner_reviewed: bool = Field(default=False) learner_reviewed_date: Optional[date] = None # Relationships learner: Optional["Learner"] = Relationship(back_populates="assessments") # ============================================================================ # Case Logs # ============================================================================ class CaseLog(TenantMixin, TimestampMixin, SQLModel, table=True): """ Clinical case log entry for procedure/encounter tracking. Clinical Context: ACGME requires minimum case numbers for graduation Performance: Fast aggregation for case count reports """ __tablename__ = "case_logs" __table_args__ = {"schema": "educa", "extend_existing": True} id: str = Field(primary_key=True) learner_id: str = Field(foreign_key="educa.learners.id", index=True) rotation_id: Optional[str] = Field(default=None, foreign_key="educa.rotations.id", index=True) # Case details case_date: date = Field(index=True) case_type: str = Field(max_length=200) # Procedure, Patient Encounter, etc. procedure_code: Optional[str] = Field(default=None, max_length=50) # CPT code diagnosis_code: Optional[str] = Field(default=None, max_length=50) # ICD-10 # Patient demographics (de-identified) patient_age: Optional[int] = None patient_gender: Optional[str] = Field(default=None, max_length=50) # Learner role role: str = Field(max_length=100) # Observer, Assistant, Performer, Supervisor level_of_supervision: str = Field(max_length=100) # Clinical details setting: str = Field(max_length=200) # OR, Clinic, ER, ICU, etc. complexity: Optional[str] = Field(default=None, max_length=50) # Low, Medium, High # Outcomes complications: bool = Field(default=False) complication_description: Optional[str] = None # Verification is_verified: bool = Field(default=False) verified_by: Optional[str] = None # Supervising attending verified_at: Optional[datetime] = None # ============================================================================ # Pydantic Schemas for API Responses # ============================================================================ class LearnerSummary(SQLModel): """Summary of learner status and progress""" learner_id: str name: str program: str year_of_training: int current_rotation: Optional[str] duty_hours_this_week: float duty_hours_compliant: bool competency_level_avg: float assessments_completed: int class DutyHourComplianceReport(SQLModel): """Duty hour compliance report for program directors""" week_start: date week_end: date total_learners: int compliant_learners: int non_compliant_learners: int average_weekly_hours: float max_weekly_hours: float violations: List[Dict[str, Any]] class CompetencyProgressReport(SQLModel): """Competency milestone progress for learner""" learner_id: str competency_domain: str current_level: CompetencyLevel assessments_count: int last_assessment_date: date trend: str # "improving", "stable", "declining" next_milestone: Optional[str]