diff --git a/config/.env.example b/config/.env.example
index 5426d447a784b124b6016b81431cc18e973ff96b..b6df30b60223eb5efd30f365385e3ba55f3b9c87 100644
--- a/config/.env.example
+++ b/config/.env.example
@@ -76,9 +76,7 @@ EDUCA_DB_NAME=educa_dev
INSURA_ENABLED=true
INSURA_DB_NAME=insura_dev
-# Movit - Medical Logistics
-MOVIT_ENABLED=true
-MOVIT_DB_NAME=movit_dev
+# Medical Logistics consolidated into Movio/Stoka
# =============================================================================
# SECURITY SETTINGS
diff --git a/config/app.yml b/config/app.yml
index 08c1790691e6aafda59f68cbc288274c03789f53..1c8f950817e69b1961d9106fb7478014fecdbc48 100644
--- a/config/app.yml
+++ b/config/app.yml
@@ -106,7 +106,7 @@ applications:
- clinica # Clinical data
- educa # Medical education
- insura # Insurance analytics
- - movit # Medical logistics
+ # movit removed - logistics consolidated into Movio and Stoka apps
# Infrastructure services
services:
diff --git a/data/seeds/README.md b/data/seeds/README.md
index d88987bd75c09aece997a3318276a6067be8288b..d087b2bf8355675cf8c7c81ffbe020626ab5be89 100644
--- a/data/seeds/README.md
+++ b/data/seeds/README.md
@@ -55,7 +55,7 @@ This directory contains seed data for the governance model (Legal Entity โ Sys
**Categories**:
- **Clinical Operations** (5 tools): surgio, clinica, labo, hospi, pharma
-- **Support Services** (10 tools): educa, insura, movio, stoka, campo, banko, lodger, fabrica, trena
+- **Support Services** (9 tools): educa, insura, movio, stoka, campo, banko, lodger, fabrica
- **Platform Services** (3 tools): admin, auth, analytics
**Key Fields**:
diff --git a/data/seeds/governance_seed.py b/data/seeds/governance_seed.py
index 1a268fc2f70ed64279a54720f97280f4f00664a4..090ed776de753ece5ad8f1444622424e2f3b15a7 100644
--- a/data/seeds/governance_seed.py
+++ b/data/seeds/governance_seed.py
@@ -274,18 +274,6 @@ TOOLS = [
"color": "#7F8C8D",
"sort_order": 13,
},
- {
- "id": UUID("20000000-0000-0000-0000-000000000014"),
- "slug": "trena",
- "display_name": "Trena",
- "description": "Training coordination",
- "category": "support_services",
- "module_path": "apps.trena",
- "is_active": True,
- "icon": "training",
- "color": "#1ABC9C",
- "sort_order": 14,
- },
# Platform Services
{
"id": UUID("20000000-0000-0000-0000-000000000015"),
diff --git a/data/seeds/system_tools.py b/data/seeds/system_tools.py
index d9d8c13b1c2de0b975919f2a6035e4b099ec8b08..94b8378568c29a2205ff0879db9ec3011f81d28e 100644
--- a/data/seeds/system_tools.py
+++ b/data/seeds/system_tools.py
@@ -22,7 +22,6 @@ SYSTEM_TOOL_SEEDS = [
{"system_slug": "yaz", "tool_slug": "banko", "enabled": True, "config": {"payment_gateway": "stripe"}},
{"system_slug": "yaz", "tool_slug": "lodger", "enabled": True, "config": {"booking_confirmations": True}},
{"system_slug": "yaz", "tool_slug": "fabrica", "enabled": True, "config": {"batch_qc_required": True}},
- {"system_slug": "yaz", "tool_slug": "trena", "enabled": True, "config": {"certification_reminders": True}},
{"system_slug": "yaz", "tool_slug": "admin", "enabled": True, "config": {"audit_retention_days": 2555}},
{"system_slug": "yaz", "tool_slug": "auth", "enabled": True, "config": {"mfa_required": True, "session_timeout_minutes": 480}},
{"system_slug": "yaz", "tool_slug": "analytics", "enabled": True, "config": {"realtime_refresh_seconds": 30}},
diff --git a/data/seeds/tools.py b/data/seeds/tools.py
index f3023f1cc68290c964e3f58bb96f22d8492691f8..671e370a2e77077420a3c3c9ac94e27e698403ed 100644
--- a/data/seeds/tools.py
+++ b/data/seeds/tools.py
@@ -196,20 +196,6 @@ TOOL_SEEDS = [
"typical_users": ["production_managers", "quality_engineers", "manufacturing_staff"]
}
},
- {
- "slug": "trena",
- "display_name": "Trena",
- "description": "Training coordination. Staff training, continuing education, certification tracking, competency assessment.",
- "module_path": "apps.trena",
- "category": "support_services",
- "version": "2.6.3",
- "is_active": True,
- "tags": ["training", "continuing_education", "certification", "competency"],
- "metadata": {
- "features": ["course_management", "certification_tracking", "competency_assessment", "training_scheduling"],
- "typical_users": ["training_coordinators", "HR_staff", "department_managers"]
- }
- },
# Platform Services
{
diff --git a/docs/architecture/CODEBASE_CREATION_SUMMARY.md b/docs/architecture/CODEBASE_CREATION_SUMMARY.md
deleted file mode 100644
index 1f36479fe06e0758870a428c6b34f091d6129555..0000000000000000000000000000000000000000
--- a/docs/architecture/CODEBASE_CREATION_SUMMARY.md
+++ /dev/null
@@ -1,424 +0,0 @@
-# Codebase Creation Logic - Implementation Summary
-
-**Date**: December 28, 2025
-**Version**: 2.0
-**Status**: โ
COMPLETE
-
----
-
-## ๐ฏ Overview
-
-Successfully revised and implemented comprehensive codebase creation logic ensuring **reproducibility, modularity, future-proofing, and scalability** for the YAZ Care Platform.
-
----
-
-## ๐ Deliverables
-
-### 1. Enhanced Documentation
-
-#### `docs/architecture/CODEBASE_CREATION_LOGIC.md` (v2.0)
-**Status**: โ
COMPLETE (706 โ 900+ lines)
-
-**Key Additions**:
-- **4 Core Principles** with detailed explanations:
- - Reproducibility (90% automation via templates)
- - Modularity (Level 0-3 hierarchy, event-driven)
- - Future-Proofing (API versioning, feature flags)
- - Scalability (horizontal scaling, 4-tier caching)
-
-- **5-Phase Creation Workflow**:
- - Phase 1: Planning & Design (decision matrix, governance alignment)
- - Phase 2: Code Generation (automated templates)
- - Phase 3: Testing & Validation (85%+ coverage)
- - Phase 4: Continuous Improvement (automatic platform upgrades)
- - Phase 5: Deployment & Registration (zero-downtime)
-
-- **Comprehensive Templates**:
- - Domain Model template (320+ lines with TenantMixin, TimestampMixin, SoftDeleteMixin)
- - API Schema template (180+ lines with OpenAPI examples)
- - Service template (240+ lines with BaseService inheritance)
- - Routes template (200+ lines with RBAC, rate limiting)
-
-- **Validation Matrices**:
- - 21-point pre-merge checklist
- - Governance alignment verification
- - Multi-tenancy isolation testing
- - Performance target validation
-
----
-
-### 2. Tool Generator Script
-
-#### `scripts/generators/create_tool.py`
-**Status**: โ
COMPLETE (600+ lines)
-
-**Features**:
-- **One-command generation**: Creates complete tool structure
-- **Standardized templates**: 7 file templates (models, schemas, routes, services, tests)
-- **Automatic configuration**: Module path, database schema, imports
-- **Clinical context**: Standards compliance, performance targets in docstrings
-- **Multi-tenancy by default**: TenantMixin, TimestampMixin, SoftDeleteMixin
-
-**Usage**:
-```bash
-python scripts/generators/create_tool.py \
- --name mednote \
- --display-name "MedNote (Clinical Documentation)" \
- --category clinical \
- --standards "HL7 FHIR,21 CFR Part 11" \
- --description "Electronic clinical documentation"
-```
-
-**Generated Structure**:
-```
-apps/mednote/
-โโโ __init__.py # Auto-generated exports
-โโโ models.py # Domain models with TenantMixin
-โโโ schemas.py # Pydantic schemas with examples
-โโโ routes.py # FastAPI routes with RBAC
-โโโ services/
-โ โโโ __init__.py
-โ โโโ mednote_service.py # BaseService inheritance
-โโโ adapters/
-โ โโโ __init__.py # Event-driven adapters
-โโโ events/
-โ โโโ __init__.py # Domain events
-โโโ tests/
- โโโ __init__.py # Test scaffolding
-```
-
----
-
-### 3. Validation Scripts
-
-#### `scripts/validation/check_governance.py`
-**Status**: โ
COMPLETE (250+ lines)
-
-**Validates**:
-- โ
Tool registered in `governance.tools` table
-- โ
Valid module path (`apps.{tool_name}`)
-- โ
Module can be imported
-- โ
Router exported from `__init__.py`
-- โ
Slug follows naming conventions (lowercase, no spaces)
-- โ
Tool enabled for at least one system
-- โ
Valid category (clinical/financial/logistics/support/platform)
-- โ
Semantic versioning (major.minor.patch)
-- โ
Code directory exists
-- โ
Required files present
-
-**Usage**:
-```bash
-python scripts/validation/check_governance.py --tool mednote
-```
-
-#### `scripts/validation/check_structure.py`
-**Status**: โ
COMPLETE (220+ lines)
-
-**Validates**:
-- โ
Required files (`__init__.py`, `models.py`, `schemas.py`, `routes.py`)
-- โ
Recommended directories (`services/`, `adapters/`, `events/`)
-- โ
File naming conventions (snake_case)
-- โ
Import structure (router exported)
-- โ
Test directory exists (`tests/apps/{tool_name}/`)
-- โ
Recommended test files present
-
-**Usage**:
-```bash
-python scripts/validation/check_structure.py --tool mednote
-```
-
----
-
-### 4. Updated AI Coder Instructions
-
-#### `.github/copilot-instructions.md`
-**Status**: โ
COMPLETE (100+ lines updated)
-
-**Key Updates**:
-- **5-Phase Workflow** integrated into AI instructions
-- **Decision Matrix** for entity layer identification
-- **Governance Alignment** rules (CRITICAL section)
-- **Code Generation** commands and patterns
-- **Validation Checklist** before merging
-- **Continuous Improvement** patterns
-- **Architecture Hierarchy** (LegalEntity โ System โ Tenant โ User โ Tool)
-- **Allowed/Forbidden** code patterns
-
-**New Sections**:
-```markdown
-## Phase 1: Planning & Design (BEFORE CODE)
-## Phase 2: Code Generation (STANDARDIZED)
-## Phase 3: Testing & Validation
-## Phase 4: Continuous Improvement (AUTOMATIC)
-## Phase 5: Deployment & Registration
-```
-
----
-
-## ๐ง Implementation Details
-
-### Core Principles Implementation
-
-#### 1. Reproducibility (90% Automation)
-**Implementation**:
-- โ
`create_tool.py` generates 7 standardized files
-- โ
Templates use Python f-strings for customization
-- โ
Identical file structure across all 17 tools
-- โ
Version-controlled templates (no manual variations)
-
-**Impact**:
-- New tool creation: 2 hours โ 15 minutes (88% time reduction)
-- Consistency: 100% (all tools follow same patterns)
-- Onboarding: New developers productive in 1 day vs 3 days
-
-#### 2. Modularity (Event-Driven Architecture)
-**Implementation**:
-- โ
Level 0-3 dependency hierarchy enforced
-- โ
Event-driven communication (no direct service calls)
-- โ
Configuration in database (not hardcoded)
-- โ
BaseService, BaseRepository for shared logic
-
-**Impact**:
-- Parallel development: 10+ teams work independently
-- Failure isolation: One tool crash doesn't affect others
-- Deployment flexibility: Individual tool updates without platform restart
-
-#### 3. Future-Proofing (Backward Compatibility)
-**Implementation**:
-- โ
API versioning (`/api/v1`, `/api/v2`)
-- โ
Migration paths documented
-- โ
Feature flags (tenant-level control)
-- โ
Deprecation warnings (6-month notice)
-
-**Impact**:
-- Breaking changes: 0 in last 6 months
-- Client migration time: 6 months for v1 โ v2
-- Customer satisfaction: 95%+ (no forced upgrades)
-
-#### 4. Scalability (Horizontal Scaling)
-**Implementation**:
-- โ
Stateless services (session in Redis/PostgreSQL)
-- โ
Schema-per-tenant (10,000+ tenants supported)
-- โ
4-tier caching (80%+ hit rate)
-- โ
Async event processing (100,000+ events/sec)
-
-**Impact**:
-- User growth: 10x without refactoring
-- Tenant capacity: 100 โ 10,000 tenants
-- Performance: <200ms p95 maintained at scale
-
----
-
-## ๐ Validation Matrix
-
-### Pre-Merge Checklist (21 Points)
-
-| Category | Requirement | Status |
-|----------|-------------|--------|
-| **Governance** | Tool registered in governance.tools | โ |
-| **Governance** | SystemTool enablement configured | โ |
-| **Governance** | Module path valid (`apps.{tool}`) | โ |
-| **Structure** | Standardized file structure | โ |
-| **Structure** | Required files present | โ |
-| **Models** | TenantMixin included | โ |
-| **Models** | TimestampMixin included | โ |
-| **Models** | SoftDeleteMixin included | โ |
-| **Models** | Foreign keys indexed | โ |
-| **Schemas** | Clinical context documented | โ |
-| **Schemas** | Standards compliance listed | โ |
-| **Schemas** | Performance targets specified | โ |
-| **Schemas** | OpenAPI examples included | โ |
-| **Events** | Event publisher implemented | โ |
-| **Events** | Repository adapter wraps CRUD | โ |
-| **Tests** | 85%+ code coverage | โ |
-| **Tests** | Multi-tenancy isolation verified | โ |
-| **Tests** | Performance targets validated | โ |
-| **Tests** | Security tests pass | โ |
-| **Docs** | API documentation complete | โ |
-| **Docs** | Migration guide included | โ |
-
----
-
-## ๐ Quick Start Examples
-
-### Example 1: Create New Clinical Tool
-
-```bash
-# Step 1: Generate tool structure (15 seconds)
-python scripts/generators/create_tool.py \
- --name cardio \
- --display-name "Cardio (Cardiology Management)" \
- --category clinical \
- --standards "ACC/AHA Guidelines,HL7 FHIR" \
- --description "Cardiology patient management and ECG interpretation"
-
-# Step 2: Validate structure (5 seconds)
-python scripts/validation/check_structure.py --tool cardio
-
-# Step 3: Customize models (10 minutes)
-# Edit: src/apps/cardio/models.py
-# Add: ECG, EchoReport, StressTest models
-
-# Step 4: Implement services (30 minutes)
-# Edit: src/apps/cardio/services/cardio_service.py
-# Add: ECG interpretation, risk stratification logic
-
-# Step 5: Register tool (10 seconds)
-python scripts/governance/register_tool.py \
- --slug cardio \
- --module-path apps.cardio \
- --system-slug yaz
-
-# Step 6: Create migration (30 seconds)
-alembic revision --autogenerate -m "Add cardio tool"
-
-# Step 7: Deploy (1 minute)
-alembic upgrade head
-python scripts/governance/seed_tools.py --tool cardio
-
-# Step 8: Validate governance (10 seconds)
-python scripts/validation/check_governance.py --tool cardio
-
-# Total time: ~45 minutes (vs 2 hours manual)
-```
-
-### Example 2: Validate Existing Tool
-
-```bash
-# Validate governance alignment
-python scripts/validation/check_governance.py --tool surgio
-
-# Expected output:
-# โ
Tool 'surgio' found in database
-# โ
Module path valid: apps.surgio
-# โ
Module can be imported
-# โ
Router properly exported
-# โ
Tool enabled for systems: yaz
-# โ
Valid category: clinical
-# โ
Valid version: 5.0.5
-# โ
Code directory exists
-# โ
All required files present
-
-# Validate file structure
-python scripts/validation/check_structure.py --tool surgio
-
-# Expected output:
-# โ
Tool directory exists
-# โ
models.py exists
-# โ
schemas.py exists
-# โ
routes.py exists
-# โ
services/ directory exists
-# โ
tests/ directory exists
-```
-
----
-
-## ๐ Documentation Reference
-
-### Updated Documents
-1. โ
`docs/architecture/CODEBASE_CREATION_LOGIC.md` (v2.0)
-2. โ
`.github/copilot-instructions.md` (updated section)
-3. โ
`scripts/generators/create_tool.py` (new)
-4. โ
`scripts/validation/check_governance.py` (new)
-5. โ
`scripts/validation/check_structure.py` (new)
-
-### Related Documents
-- `docs/architecture/GOVERNANCE_MODEL.md` - Legal Entity โ System โ Tenant โ Tool architecture
-- `docs/06-sprints/sprint-33-event-driven-architecture.md` - Event consumers framework
-- `docs/03-development/testing-guide.md` - Test coverage standards
-
----
-
-## ๐ Training & Adoption
-
-### For AI Coders (Copilot/Claude)
-- โ
Updated instructions integrated into `.github/copilot-instructions.md`
-- โ
5-phase workflow now mandatory for all entity creation
-- โ
Decision matrix guides entity layer selection
-- โ
Validation checklist prevents non-compliant merges
-
-### For Human Developers
-- โ
Tool generator reduces manual work by 88%
-- โ
Validation scripts provide immediate feedback
-- โ
Comprehensive documentation with examples
-- โ
Pre-written templates ensure consistency
-
-### For Platform Team
-- โ
Continuous improvement via BaseService/BaseRepository
-- โ
Platform upgrades propagate to all tools automatically
-- โ
Event-driven architecture enables parallel development
-- โ
Governance model separates business from code
-
----
-
-## ๐ฎ Future Enhancements
-
-### Phase 2 (Q1 2026)
-- [ ] Add `create_domain_model.py` for individual models
-- [ ] Add `create_api_endpoint.py` for single routes
-- [ ] Integrate with GitHub Actions for automated validation
-- [ ] Create VS Code extension for one-click generation
-
-### Phase 3 (Q2 2026)
-- [ ] Add performance benchmarking script
-- [ ] Add security scanning script
-- [ ] Create compliance report generator
-- [ ] Build tool dependency visualizer
-
----
-
-## ๐ Metrics & KPIs
-
-### Before Revision
-- Tool creation time: 2 hours (manual)
-- Consistency: 70% (manual variations)
-- Documentation: 50% complete
-- Test coverage: 74%
-- Validation: Manual code review
-
-### After Revision (v2.0)
-- Tool creation time: 15 minutes (88% reduction)
-- Consistency: 100% (template-driven)
-- Documentation: 100% complete (auto-generated)
-- Test coverage: 85%+ target
-- Validation: Automated scripts (2 scripts)
-
-### Impact
-- **Development velocity**: 8x faster tool creation
-- **Code quality**: 100% consistent patterns
-- **Maintenance burden**: 60% reduction (standardized structure)
-- **Onboarding time**: 67% reduction (clear templates)
-
----
-
-## โ
Completion Checklist
-
-- [x] Enhanced CODEBASE_CREATION_LOGIC.md (v2.0)
-- [x] Created tool generator script (create_tool.py)
-- [x] Created governance validation script (check_governance.py)
-- [x] Created structure validation script (check_structure.py)
-- [x] Updated AI coder instructions
-- [x] Verified BaseService/BaseRepository exist
-- [x] Created implementation summary (this document)
-- [x] Tested tool generation workflow
-- [x] Tested validation scripts
-
----
-
-## ๐ Summary
-
-Successfully implemented comprehensive codebase creation logic with:
-- **4 Core Principles**: Reproducibility, Modularity, Future-Proofing, Scalability
-- **5-Phase Workflow**: Planning โ Generation โ Testing โ Improvement โ Deployment
-- **3 Automation Scripts**: Tool generator + 2 validation scripts
-- **100% Consistency**: All tools follow identical patterns
-- **88% Time Savings**: 2 hours โ 15 minutes per tool
-
-The platform now has a **repeatable, scalable, and maintainable** process for creating entities/tools that **continuously improves** as platform capabilities evolve.
-
----
-
-**Document Owner**: Platform Architecture Team
-**Last Updated**: December 28, 2025
-**Next Review**: January 28, 2026
-**Version**: 2.0
diff --git a/docs/architecture/README.md b/docs/architecture/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..2db5d59b2c10547469bc1c389dbedb5c46253c61
--- /dev/null
+++ b/docs/architecture/README.md
@@ -0,0 +1,221 @@
+# Architecture Documentation
+
+**YAZ Care Platform - Healthcare Software Architecture**
+**Version**: 5.0.5
+**Last Updated**: December 31, 2025
+
+---
+
+## ๐ Documentation Index
+
+This directory contains the complete architectural documentation for the YAZ Care Platform. All documentation follows production standards with comprehensive examples and best practices.
+
+### Core Architecture Documents
+
+#### 1. **[Codebase Creation Logic](./CODEBASE_CREATION_LOGIC.md)**
+**Size**: 627 lines | **Status**: โ
Production Standard
+
+Complete guide for creating new entities, apps, and tools following the platform's standardized workflow.
+
+**Topics Covered**:
+- 4 Core Principles (Reproducibility, Modularity, Future-Proofing, Scalability)
+- 5-Phase Creation Workflow (Planning โ Generation โ Testing โ Improvement โ Deployment)
+- Entity Layer Decision Matrix (LegalEntity, System, Tenant, User, Tool, Model, Service, API)
+- Domain Model, API Schema, Service, and Route patterns
+- 21-point Validation Checklist
+
+**Use When**: Creating new apps, adding domain models, implementing services
+
+---
+
+#### 2. **[App Standardization Guide](./APP_STANDARDIZATION.md)**
+**Size**: 552 lines | **Status**: โ
Production Standard
+
+Standardization patterns for all 17 healthcare applications ensuring coherence and homogeneity.
+
+**Topics Covered**:
+- Sprint 35 Progress (45% complete - Phase 2 UI/UX templates generated)
+- Domain Model Pattern (SQLModel + TenantMixin + TimestampMixin + SoftDeleteMixin)
+- API Schema Pattern (Pydantic V2 with validation)
+- Route Pattern (FastAPI with HTMX endpoints)
+- Service Pattern (Business logic with BaseService)
+- UI Template Pattern (HTMX + Alpine.js)
+- Implementation Workflow (5 phases)
+- Validation Checklist
+
+**Use When**: Implementing new apps, standardizing existing code, ensuring consistency
+
+---
+
+#### 3. **[UI/UX System](./UI_UX_SYSTEM.md)**
+**Size**: 357 lines โ **Updated to 600+ lines** | **Status**: โ
Production Standard
+
+Modular UI/UX system with complete dark mode support and WCAG 2.1 AA accessibility compliance.
+
+**Topics Covered**:
+- 4 Core Principles (Homogeneity, Coherence, Modularity, Reproducibility)
+- Template Hierarchy (base.html โ app_base.html โ {app}_new.html)
+- Component Library (App Header, Navigation Tabs, Stats Grid)
+- Design System (Color Palette, Typography, Spacing)
+- **Dark Mode Implementation** (Complete patterns for all components)
+- **Accessibility** (WCAG 2.1 AA compliance with ARIA, semantic HTML, keyboard nav)
+- Creating New Apps (3-step process)
+- Migration Guide
+- Testing Checklist (Functionality, Dark Mode, Accessibility, Responsive)
+
+**Use When**: Creating UI templates, implementing dark mode, ensuring accessibility
+
+---
+
+#### 4. **[Governance Model](./GOVERNANCE_MODEL.md)**
+**Size**: 458 lines | **Status**: โ
Production Standard
+
+Multi-tenant architecture separating business entities from code structure.
+
+**Topics Covered**:
+- 4-Layer Architecture (LegalEntity โ System โ Tool โ SystemTool)
+- Critical Principle: Legal entities/systems are DATABASE METADATA, not code structure
+- Data Flow (Startup sequence, Request flow)
+- Database Schema (5 tables: legal_entities, systems, tools, system_tools, tenants)
+- Security Model (Access control matrix, Audit logging)
+- Implementation Status (Phase 2 complete, Phase 3 next)
+
+**Use When**: Understanding multi-tenancy, system configuration, tool enablement
+
+---
+
+#### 5. **[Practical Examples](./PRACTICAL_EXAMPLES.md)**
+**Size**: 734 lines | **Status**: โ
Production Standard
+
+Real-world, copy-paste ready code examples for common development tasks.
+
+**Topics Covered**:
+- Task Templates (Create domain model, Implement API schema, Create HTMX routes, Add clinical algorithm)
+- Complete Feature Example: High-Risk Surgery Alert System
+ - Domain Model (with TenantMixin, clinical context)
+ - API Schemas (Create, Update, Response, List)
+ - Service Implementation (risk calculation algorithm with ASA criteria)
+ - Route Endpoints (HTMX-powered CRUD)
+ - Comprehensive Tests (unit, integration, isolation, performance)
+- Implementation Checklists
+
+**Use When**: Starting new features, need code examples, implementing clinical algorithms
+
+---
+
+## ๐ฏ Quick Navigation
+
+### By Task Type
+
+**Starting a New Project**:
+1. Read [Codebase Creation Logic](./CODEBASE_CREATION_LOGIC.md) - Planning & workflow
+2. Review [App Standardization](./APP_STANDARDIZATION.md) - Implementation patterns
+3. Use [Practical Examples](./PRACTICAL_EXAMPLES.md) - Copy-paste code
+
+**Building UI/UX**:
+1. Read [UI/UX System](./UI_UX_SYSTEM.md) - Design system & components
+2. Review Dark Mode section - Implementation patterns
+3. Check Accessibility section - WCAG 2.1 AA compliance
+
+**Understanding Architecture**:
+1. Read [Governance Model](./GOVERNANCE_MODEL.md) - Multi-tenancy & layers
+2. Review [Codebase Creation Logic](./CODEBASE_CREATION_LOGIC.md) - Entity decisions
+3. Check [App Standardization](./APP_STANDARDIZATION.md) - Code patterns
+
+### By Role
+
+**Backend Developer**:
+- [Codebase Creation Logic](./CODEBASE_CREATION_LOGIC.md) - Domain models, services, routes
+- [App Standardization](./APP_STANDARDIZATION.md) - API schemas, service patterns
+- [Practical Examples](./PRACTICAL_EXAMPLES.md) - Complete implementations
+- [Governance Model](./GOVERNANCE_MODEL.md) - Multi-tenancy
+
+**Frontend Developer**:
+- [UI/UX System](./UI_UX_SYSTEM.md) - Templates, components, dark mode
+- [App Standardization](./APP_STANDARDIZATION.md) - HTMX patterns
+- [Practical Examples](./PRACTICAL_EXAMPLES.md) - UI examples
+
+**DevOps/Platform Engineer**:
+- [Governance Model](./GOVERNANCE_MODEL.md) - System configuration
+- [Codebase Creation Logic](./CODEBASE_CREATION_LOGIC.md) - Deployment phase
+- [App Standardization](./APP_STANDARDIZATION.md) - Infrastructure requirements
+
+---
+
+## ๐ Documentation Statistics
+
+**Total Documents**: 5 core architecture guides
+**Total Lines**: ~3,300 lines of comprehensive documentation
+**Status**: All production-ready with v2.0 standards
+**Last Major Update**: December 31, 2025 (Dark mode & accessibility consolidation)
+
+### Recent Changes
+
+**December 31, 2025**:
+- โ
Consolidated duplicate documentation
+- โ
Removed 4 redundant summary files
+- โ
Merged UI/UX Dark Mode Guide into UI/UX System
+- โ
Enhanced UI/UX System with complete dark mode and accessibility sections
+- โ
Created this comprehensive README index
+
+**December 30, 2025**:
+- โ
Generated UI/UX templates for all 14 healthcare apps
+- โ
Completed Phase 3 (UI templates) of Sprint 35
+
+**December 28, 2025**:
+- โ
Created Codebase Creation Logic v2.0
+- โ
Implemented tool generator script
+
+---
+
+## ๐ Related Documentation
+
+### Project Management
+- [Sprint Documentation](../06-sprints/) - Current sprint progress
+- [TODO.md](../TODO.md) - Active task list
+- [STATUS.md](../STATUS.md) - Project status
+
+### Development
+- [Getting Started](../02-getting-started/) - Setup instructions
+- [Development Guide](../03-development/) - Coding standards
+- [API Reference](../05-api-reference/) - API documentation
+
+### Operations
+- [Operations Guide](../07-operations/) - Deployment procedures
+- [Optimization](../08-optimization/) - Performance tuning
+
+---
+
+## ๐ค Contributing
+
+When updating architecture documentation:
+
+1. **Follow Standards**: All docs must follow v2.0 production standards
+2. **Update Version**: Increment version number and last updated date
+3. **Cross-Reference**: Link to related documentation
+4. **Add Examples**: Include practical, copy-paste ready examples
+5. **Update Index**: Add new docs to this README
+
+### Documentation Standards
+
+- โ
**Clinical Context**: Include healthcare workflow descriptions
+- โ
**Standards Compliance**: Reference CLSI/ASA/WHO/HL7/FDA/ISO standards
+- โ
**Performance Targets**: Document <50ms/<100ms/<200ms SLAs
+- โ
**Security**: RBAC roles, audit logging, PHI protection
+- โ
**Code Examples**: Production-ready, with type hints and docstrings
+- โ
**Checklists**: Validation checklists for implementation
+
+---
+
+## ๐ Support
+
+**Questions or Issues?**
+- Check [Practical Examples](./PRACTICAL_EXAMPLES.md) for code samples
+- Review [.github/copilot-instructions.md](../../.github/copilot-instructions.md) for AI coding guidelines
+- See [CONTRIBUTING.md](../../CONTRIBUTING.md) for contribution process
+
+---
+
+**Maintained By**: YAZ Care Development Team
+**Version**: 5.0.5
+**Status**: Production - All Core Docs Complete
diff --git a/docs/architecture/UI_UX_STANDARDIZATION_COMPLETE.md b/docs/architecture/UI_UX_STANDARDIZATION_COMPLETE.md
deleted file mode 100644
index 9d0bf80462665755be990ee247a8fd39504da863..0000000000000000000000000000000000000000
--- a/docs/architecture/UI_UX_STANDARDIZATION_COMPLETE.md
+++ /dev/null
@@ -1,613 +0,0 @@
-# YAZ Care Platform - UI/UX Standardization Complete ๐จ
-
-**Date**: December 29, 2025
-**Status**: โ
COMPLETE
-**Scope**: All 14 healthcare apps + 3 platform apps
-**Generated**: 14 templates + 14 route boilerplates = **28 standardized files**
-
----
-
-## ๐ Executive Summary
-
-Successfully generated homogeneous, coherent UI/UX templates for all 17 YAZ Care applications following enterprise healthcare design standards. Each app now has:
-
-1. โ
**Standardized HTML templates** with HTMX + Alpine.js
-2. โ
**Route boilerplate code** with open-source CRUD operations
-3. โ
**App-specific branding** (gradients, icons, entity names)
-4. โ
**Consistent component structure** (stats, search, tables, tabs)
-5. โ
**Placeholder hooks** for proprietary AI features
-
-**Total Generated Code**: ~28,000 lines of production-ready UI/UX code
-
----
-
-## ๐ฏ Standardization Principles Applied
-
-### 1. **Homogeneity** - Consistent User Experience
-- Identical layout structure across all apps
-- Unified navigation patterns (tabs, breadcrumbs)
-- Standardized component library (stats cards, search bars, tables)
-- Consistent spacing, typography, and responsive breakpoints
-
-### 2. **Coherence** - Logical Design System
-- App-specific color gradients for visual identity
-- Icon system using Font Awesome
-- Semantic naming conventions (dashboard, cases, analytics)
-- Predictable interaction patterns
-
-### 3. **Modularity** - Reusable Components
-- Template inheritance: `base.html` โ `app_base.html` โ `{app}_new.html`
-- Shared components: `app_header`, `app_tabs`, `stats_grid`
-- Component-based architecture enables rapid iteration
-
-### 4. **Accessibility** - WCAG 2.1 AA Compliance
-- Semantic HTML5 elements
-- ARIA labels and roles
-- Keyboard navigation support
-- Color contrast ratios >4.5:1
-
-### 5. **Performance** - Optimized Loading
-- HTMX for partial page updates (reduce bandwidth by 80%)
-- Lazy loading for charts and heavy components
-- CSS/JS minification and compression
-- Target: <200ms p95 latency for all UI interactions
-
----
-
-## ๐๏ธ Generated Templates Structure
-
-### Template Anatomy
-
-Each `{app}_new.html` template contains:
-
-```jinja2
-{%extends "shared/app_base.html" %}
-
-{%block title %}{App Name} - {Description}{%endblock %}
-
-{%set app_config = {
- 'slug': 'app_slug',
- 'name': 'App Name',
- 'entity_name': 'Primary Entity',
- 'icon': '๐จ',
- 'gradient_from': '#667eea',
- 'gradient_to': '#764ba2'
-} %}
-
-{%set app_tabs = [
- {'id': 'dashboard', 'label': 'Dashboard', 'icon': 'tachometer-alt'},
- {'id': 'cases', 'label': 'Cases', 'icon': 'list'},
- {'id': 'analytics', 'label': 'Analytics', 'icon': 'chart-line'}
-] %}
-
-{%set stats = [
- {/* 4 statistical cards with trends */}
-] %}
-
-{%block dashboard_content %}
-
-
-
-{%endblock %}
-
-{%block additional_tabs %}
-
-
-{%endblock %}
-
-{%block app_scripts %}
-
-{%endblock %}
-```
-
----
-
-## ๐ฆ Apps Standardized (14 Healthcare + 3 Platform)
-
-### Clinical Operations (5 Apps)
-
-#### 1. Surgio ๐ช - Advanced Surgical Management
-- **Gradient**: Purple (#667eea โ #764ba2)
-- **Entity**: Surgery Case
-- **Tabs**: Dashboard | Cases | OR Schedule | Analytics
-- **Features**: CRUD, Search, Export, Analytics
-- **Standards**: ASA, WHO Surgical Safety Checklist
-
-#### 2. Clinica ๐ฅ - Clinical Data Management
-- **Gradient**: Pink-Red (#f093fb โ #f5576c)
-- **Entity**: Patient
-- **Tabs**: Dashboard | Patients | Encounters | Vitals
-- **Features**: CRUD, Search, Export, FHIR
-- **Standards**: HL7 FHIR, ICD-10
-
-#### 3. Labo ๐ฌ - Laboratory Information System
-- **Gradient**: Green (#43e97b โ #38f9d7)
-- **Entity**: Test
-- **Tabs**: Dashboard | Tests | Results | Quality Control
-- **Features**: CRUD, Search, Export, QC Charts
-- **Standards**: CLSI, CAP
-
-#### 4. Hospi ๐ฅ - Hospital Operations
-- **Gradient**: Blue (#6a11cb โ #2575fc)
-- **Entity**: Admission
-- **Tabs**: Dashboard | Bed Management | Admissions | Capacity
-- **Features**: CRUD, Search, Export, Capacity Planning
-- **Standards**: Joint Commission
-
-#### 5. Pharma ๐ - Pharmaceutical Management
-- **Gradient**: Cyan (#4facfe โ #00f2fe)
-- **Entity**: Prescription
-- **Tabs**: Dashboard | Prescriptions | Inventory | Interactions
-- **Features**: CRUD, Search, Export, Drug Interactions
-- **Standards**: FDA, USP
-
-### Support Services (7 Apps)
-
-#### 6. Educa ๐ - Medical Education & Training
-- **Gradient**: Peach (#fa709a โ #fee140)
-- **Entity**: Course
-- **Tabs**: Dashboard | Courses | Enrollments | Competencies
-- **Features**: CRUD, Search, Export, LMS
-- **Standards**: ACGME, CME
-
-#### 7. Insura ๐ก๏ธ - Insurance Analytics
-- **Gradient**: Teal (#30cfd0 โ #330867)
-- **Entity**: Claim
-- **Tabs**: Dashboard | Claims | Authorizations | Analytics
-- **Features**: CRUD, Search, Export, Risk Analytics
-- **Standards**: ICD-10, CPT
-
-#### 8. Movio ๐ฆ - Medical Logistics
-- **Gradient**: Pastel (#a8edea โ #fed6e3)
-- **Entity**: Inventory Item
-- **Tabs**: Dashboard | Inventory | Orders | Vendors
-- **Features**: CRUD, Search, Export, Import, Barcode
-- **Standards**: GS1, FDA UDI
-
-#### 9. Stoka ๐ - Stock Management
-- **Gradient**: Red-Pink (#f77062 โ #fe5196)
-- **Entity**: Stock Item
-- **Tabs**: Dashboard | Stock | Movements | Cycle Counts
-- **Features**: CRUD, Search, Export, Import, Cycle Counts
-- **Standards**: ISO 22095
-
-#### 10. Campo ๐ - Field Operations
-- **Gradient**: Coral (#ff6e7f โ #bfe9ff)
-- **Entity**: Program
-- **Tabs**: Dashboard | Mobile Clinics | Programs | Resources
-- **Features**: CRUD, Search, Export, GPS Tracking
-- **Standards**: WHO Field Guidelines
-
-#### 11. Banko ๐ฐ - Financial Management
-- **Gradient**: Rose (#ff9a9e โ #fecfef)
-- **Entity**: Transaction
-- **Tabs**: Dashboard | Transactions | Invoices | Reports
-- **Features**: CRUD, Search, Export, Financial Reports
-- **Standards**: GAAP, HIPAA
-
-#### 12. Lodger ๐จ - Accommodation Management
-- **Gradient**: Lavender (#e0c3fc โ #8ec5fc)
-- **Entity**: Room
-- **Tabs**: Dashboard | Rooms | Reservations | Guests
-- **Features**: CRUD, Search, Export, Booking
-- **Standards**: Hospitality standards
-
-### Manufacturing & Training (2 Apps)
-
-#### 13. Fabrica ๐ญ - Manufacturing Operations
-- **Gradient**: Peach (#ffecd2 โ #fcb69f)
-- **Entity**: Production Batch
-- **Tabs**: Dashboard | Batches | Quality Tests | Non-Conformance
-- **Features**: CRUD, Search, Export, Quality Control
-- **Standards**: FDA 21 CFR Part 820, ISO 13485
-
-#### 14. Trena ๐ - Training Coordination
-- **Gradient**: Peach (#ffecd2 โ #fcb69f)
-- **Entity**: Training Course
-- **Tabs**: Dashboard | Courses | Enrollments | Certifications
-- **Features**: CRUD, Search, Export, Compliance Tracking
-- **Standards**: Joint Commission, OSHA
-
----
-
-## ๐ง Open Source Features Implemented
-
-### 1. CRUD Operations (Create, Read, Update, Delete)
-```python
-# Auto-generated routes for every app
-@router.post("/items") # Create
-@router.get("/items") # Read (list)
-@router.get("/items/{id}") # Read (single)
-@router.patch("/items/{id}") # Update
-@router.delete("/items/{id}") # Delete (soft)
-```
-
-### 2. Search & Filtering
-- **Full-text search** across entity fields
-- **Status filtering** (active, pending, completed, cancelled)
-- **Date range filters**
-- **Multi-column sorting**
-- **HTMX-powered** (no page reloads)
-
-### 3. Export Functionality
-- **CSV Export**: Standard format for Excel/Sheets
-- **Excel Export** (TODO): Advanced formatting with openpyxl
-- **PDF Export** (TODO): Professional reports with reportlab
-
-### 4. Bulk Import
-- **CSV Import**: Upload and parse CSV files
-- **Excel Import** (TODO): Support .xlsx files
-- **Validation**: Data validation before import
-- **Transaction Safety**: Rollback on errors
-
-### 5. Pagination
-- Default 50 items per page
-- Max 1000 items per request
-- Server-side pagination for performance
-- HTMX-powered infinite scroll (optional)
-
-### 6. Analytics Dashboard
-- **Basic Charts**: Line, bar, pie charts with Chart.js
-- **Trend Analysis**: Week-over-week, month-over-month
-- **Distribution Charts**: Status breakdown
-- **Performance Metrics**: Response times, success rates
-
----
-
-## ๐ Proprietary Feature Placeholders
-
-### AI-Powered Analytics (AYRAD Fusion Integration)
-```html
-
-
-
- ๐ Coming Soon: AI-Powered Analytics
-
-
- Advanced predictive analytics, ML-driven insights,
- and automated recommendations will be available in future updates.
-
-
-```
-
-### Future Proprietary Features (Documented)
-```python
-@router.get("/analytics/advanced")
-async def get_advanced_analytics():
- """
- TODO: PROPRIETARY - Advanced AI-powered analytics
-
- Future Features:
- - Predictive modeling with ML
- - Automated insights generation
- - Trend forecasting
- - Anomaly detection
- - Optimization recommendations
-
- Dependencies:
- - AYRAD Fusion integration
- - ML model training pipeline
- - Real-time data streaming
-
- Estimated Effort: 2-3 weeks
- Priority: High
- """
- pass
-```
-
----
-
-## ๐ Component Library
-
-### Reusable UI Components
-
-#### 1. Stats Grid (`stats_grid.html`)
-```jinja2
-
- {%for stat in stats %}
-
-
-
-
{{stat.label}}
-
- {{stat.value}}
-
-
-
-
- {%if stat.trend %}
-
-
- {{stat.trend}}%
-
- {{stat.trend_text}}
-
- {%endif %}
-
- {%endfor %}
-
-```
-
-#### 2. App Header (`app_header.html`)
-```jinja2
-
-
-
-
{{app_config.icon}}
-
-
{{app_config.name}}
-
{{app_config.description}}
-
-
-
-
-```
-
-#### 3. App Tabs (`app_tabs.html`)
-```jinja2
-
-
-
-```
-
-#### 4. Search Bar (HTMX-powered)
-```html
-
-
-
-
-```
-
-#### 5. Data Table (Responsive)
-```html
-
-
-
-
- | Name |
- Status |
- Date |
- Actions |
-
-
-
-
-
-
-
-```
-
----
-
-## ๐จ Color Palette & Branding
-
-### App-Specific Gradients
-
-| App | From | To | Hex Range |
-|-----|------|----|----|
-| Surgio | Purple | Deep Purple | #667eea โ #764ba2 |
-| Clinica | Pink | Red | #f093fb โ #f5576c |
-| Labo | Green | Cyan | #43e97b โ #38f9d7 |
-| Hospi | Purple | Blue | #6a11cb โ #2575fc |
-| Pharma | Cyan | Light Blue | #4facfe โ #00f2fe |
-| Educa | Pink | Yellow | #fa709a โ #fee140 |
-| Insura | Teal | Navy | #30cfd0 โ #330867 |
-| Movio | Mint | Pink | #a8edea โ #fed6e3 |
-| Stoka | Red | Pink | #f77062 โ #fe5196 |
-| Campo | Coral | Sky Blue | #ff6e7f โ #bfe9ff |
-| Banko | Rose | Pink | #ff9a9e โ #fecfef |
-| Lodger | Lavender | Sky Blue | #e0c3fc โ #8ec5fc |
-| Fabrica | Peach | Coral | #ffecd2 โ #fcb69f |
-| Trena | Peach | Coral | #ffecd2 โ #fcb69f |
-
-### Typography
-- **Font Family**: Inter (variable font)
-- **Headings**: 700 weight (bold)
-- **Body**: 400 weight (regular)
-- **Sizes**: 12px โ 14px โ 16px โ 20px โ 24px โ 32px
-
-### Spacing System
-- **Base Unit**: 4px (0.25rem)
-- **Scale**: 4px, 8px, 12px, 16px, 24px, 32px, 48px, 64px
-- **Container**: max-width 1280px
-
----
-
-## ๐ HTMX Integration Patterns
-
-### Partial Page Updates
-```html
-
-
-
-
-```
-
-### Search with Debouncing
-```html
-
-```
-
-### Form Submission
-```html
-
-```
-
-### Infinite Scroll
-```html
-
-
-
-```
-
----
-
-## ๐ฑ Responsive Design Breakpoints
-
-```css
-/* Mobile First Approach */
-.container {
- padding: 1rem; /* Base */
-}
-
-/* Tablet (768px+) */
-@media (min-width: 768px) {
- .grid { grid-template-columns: repeat(2, 1fr); }
-}
-
-/* Desktop (1024px+) */
-@media (min-width: 1024px) {
- .grid { grid-template-columns: repeat(4, 1fr); }
-}
-
-/* Large Desktop (1280px+) */
-@media (min-width: 1280px) {
- .container { max-width: 1280px; }
-}
-```
-
----
-
-## ๐งช Testing UI Components
-
-### Visual Regression Testing (TODO)
-```bash
-# Percy.io or Chromatic
-npm run test:visual
-```
-
-### Accessibility Testing (TODO)
-```bash
-# axe-core
-npm run test:a11y
-```
-
-### Performance Testing (TODO)
-```bash
-# Lighthouse CI
-npm run test:performance
-```
-
----
-
-## ๐ฆ Next Steps & Implementation Roadmap
-
-### Phase 1: โ
COMPLETE - Template Generation
-- [x] Generate 14 app templates
-- [x] Generate 14 route boilerplates
-- [x] Document design system
-- [x] Create component library
-
-### Phase 2: ๐ IN PROGRESS - Route Implementation
-- [ ] Implement CRUD routes for each app
-- [ ] Add service layer methods
-- [ ] Create Pydantic schemas for requests/responses
-- [ ] Wire up routes to main FastAPI app
-
-### Phase 3: โณ TODO - Open Source Features
-- [ ] CSV export functionality
-- [ ] CSV import with validation
-- [ ] Excel export (openpyxl)
-- [ ] PDF export (reportlab)
-- [ ] Advanced search filters
-- [ ] Bulk operations
-
-### Phase 4: โณ TODO - Testing & Validation
-- [ ] Unit tests for routes (85%+ coverage)
-- [ ] Integration tests for UI flows
-- [ ] Visual regression tests
-- [ ] Accessibility audits
-- [ ] Performance benchmarks
-
-### Phase 5: โณ TODO - Proprietary Features
-- [ ] AYRAD Fusion integration hooks
-- [ ] ML model endpoints
-- [ ] Real-time analytics dashboards
-- [ ] Advanced AI features documentation
-- [ ] Premium feature gating
-
----
-
-## ๐ Metrics & KPIs
-
-### Code Generation Stats
-- **Templates Generated**: 14 files ร 300 lines = 4,200 LOC
-- **Route Boilerplates**: 14 files ร 200 lines = 2,800 LOC
-- **Component Library**: 5 components ร 50 lines = 250 LOC
-- **Documentation**: 3 files ร 500 lines = 1,500 LOC
-- **Total Generated**: ~8,750 lines of production code
-
-### Time Savings
-- **Manual Development**: 14 apps ร 8 hours = 112 hours
-- **Automated Generation**: 1 hour
-- **Time Saved**: 111 hours (~2.8 weeks)
-- **ROI**: 11,100% efficiency gain
-
-### Quality Metrics (Targets)
-- โ
**Consistency**: 100% (identical structure)
-- โ
**Standards Compliance**: 100% (WCAG 2.1 AA)
-- ๐ฏ **Performance**: <200ms p95 (to be tested)
-- ๐ฏ **Accessibility**: 100% (to be audited)
-- ๐ฏ **Test Coverage**: 85%+ (to be written)
-
----
-
-## ๐ Related Documentation
-
-- [UI/UX System](./UI_UX_SYSTEM.md) - Design system principles
-- [App Standardization Guide](./APP_STANDARDIZATION_GUIDE.md) - Backend standards
-- [Codebase Creation Logic](./CODEBASE_CREATION_LOGIC.md) - Architecture patterns
-- [Sprint 35 Summary](../06-sprints/current/sprint-35-app-standardization-complete.md) - Project overview
-
----
-
-## ๐ Conclusion
-
-This UI/UX standardization effort establishes a **solid foundation** for YAZ Care Platform's frontend development. Key achievements:
-
-1. โ
**Homogeneous Design**: Consistent UX across all 14 apps
-2. โ
**Rapid Development**: Templates generated in minutes vs. weeks
-3. โ
**Open Source Ready**: CRUD operations and export/import features
-4. โ
**Future-Proof**: Clear hooks for proprietary AI features
-5. โ
**Enterprise Quality**: Standards-compliant, accessible, performant
-
-**Next Priority**: Implement route handlers and connect templates to backend services.
-
----
-
-**Generated**: December 29, 2025
-**Author**: YAZ Care Development Team
-**Version**: 1.0.0
diff --git a/docs/architecture/UI_UX_SYSTEM.md b/docs/architecture/UI_UX_SYSTEM.md
deleted file mode 100644
index d865c5c6d021294a349482fcd0271ca7d4efb321..0000000000000000000000000000000000000000
--- a/docs/architecture/UI_UX_SYSTEM.md
+++ /dev/null
@@ -1,357 +0,0 @@
-# YAZ Care Platform - Modular UI/UX System
-
-## ๐ Overview
-
-This document describes the **homogeneous, coherent, and modular UI/UX system** implemented across all YAZ Care Platform healthcare applications. The system ensures consistency, maintainability, and reproducibility.
-
-## ๐ฏ Core Principles
-
-### 1. **Homogeneity**
-- All apps share the same visual language
-- Consistent color schemes and gradients
-- Unified typography and spacing
-- Standardized component structure
-
-### 2. **Coherence**
-- Logical information hierarchy
-- Predictable navigation patterns
-- Consistent user interactions
-- Unified error and success states
-
-### 3. **Modularity**
-- Reusable components
-- Template inheritance
-- DRY (Don't Repeat Yourself) approach
-- Easy to extend and maintain
-
-### 4. **Reproducibility**
-- Clear template structure
-- Documented patterns
-- Copy-paste ready templates
-- Consistent naming conventions
-
-## ๐๏ธ Architecture
-
-### Template Hierarchy
-
-```
-base.html (Foundation)
- โโโ shared/app_base.html (App Container)
- โโโ apps/{app_name}_new.html (App Implementation)
- โโโ components/*.html (Reusable Components)
-```
-
-### Component Library
-
-#### 1. **App Header** (`components/app_header.html`)
-```jinja2
-{% include 'components/app_header.html' with app_config=app_config %}
-```
-
-**Features:**
-- Back to Home button with visual feedback
-- App name and description
-- Action buttons (New, Refresh, etc.)
-- App-specific gradient backgrounds
-- Responsive design (mobile-optimized)
-
-**Usage:**
-```python
-app_config = {
- 'slug': 'surgio',
- 'name': 'Surgio',
- 'description': 'Advanced Surgical Management',
- 'entity_name': 'Surgery Case'
-}
-```
-
-#### 2. **Navigation Tabs** (`components/app_tabs.html`)
-```jinja2
-{% include 'components/app_tabs.html' with tabs=tabs %}
-```
-
-**Features:**
-- Horizontal scrolling on mobile
-- Active state management
-- Icon + label display
-- Accessible (ARIA attributes)
-
-**Usage:**
-```python
-app_tabs = [
- {'id': 'dashboard', 'label': 'Dashboard', 'icon': 'tachometer-alt'},
- {'id': 'cases', 'label': 'Cases', 'icon': 'procedures'},
- {'id': 'analytics', 'label': 'Analytics', 'icon': 'chart-line'}
-]
-```
-
-#### 3. **Stats Grid** (`components/stats_grid.html`)
-```jinja2
-{% include 'components/stats_grid.html' with stats=stats %}
-```
-
-**Features:**
-- Responsive grid layout
-- Trend indicators (up/down)
-- Color-coded metrics
-- Hover animations
-
-**Usage:**
-```python
-stats = [
- {
- 'icon': 'procedures',
- 'value': 127,
- 'label': 'Total Cases',
- 'color': '#667eea',
- 'trend': 8,
- 'trend_text': '8% this month'
- }
-]
-```
-
-## ๐จ Design System
-
-### Color Palette
-
-Each app has a unique gradient scheme:
-
-| App | Primary | Secondary | Usage |
-|-----|---------|-----------|-------|
-| **Surgio** | `#667eea` | `#764ba2` | Surgical Management |
-| **Clinica** | `#f093fb` | `#f5576c` | Clinical Data |
-| **Pharma** | `#4facfe` | `#00f2fe` | Pharmacy |
-| **Labo** | `#43e97b` | `#38f9d7` | Laboratory |
-| **Educa** | `#fa709a` | `#fee140` | Education |
-| **Insura** | `#30cfd0` | `#330867` | Insurance |
-| **Movio** | `#a8edea` | `#fed6e3` | Logistics |
-| **Banko** | `#ff9a9e` | `#fecfef` | Finance |
-| **Trena** | `#ffecd2` | `#fcb69f` | Training |
-| **Campo** | `#ff6e7f` | `#bfe9ff` | Field Ops |
-| **Lodger** | `#e0c3fc` | `#8ec5fc` | Accommodation |
-| **Stoka** | `#f77062` | `#fe5196` | Stock |
-| **Hospi** | `#6a11cb` | `#2575fc` | Hospital Ops |
-
-### Typography
-
-```css
-/* Headers */
-.app-header-title: 1.875rem, 700 weight
-.app-header-subtitle: 0.875rem, 400 weight
-
-/* Body */
-font-family: 'Inter', -apple-system, sans-serif
-line-height: 1.6
-
-/* Sizes */
-text-sm: 0.875rem
-text-base: 1rem
-text-lg: 1.125rem
-text-xl: 1.25rem
-text-2xl: 1.5rem
-```
-
-### Spacing
-
-```css
-gap-3: 0.75rem
-gap-4: 1rem
-gap-6: 1.5rem
-padding: 1.5rem (cards)
-margin-bottom: 1.5rem (sections)
-```
-
-## ๐ Creating a New App
-
-### Step 1: Create Template File
-
-```bash
-touch src/ui/templates/apps/{app_name}_new.html
-```
-
-### Step 2: Use the Template Structure
-
-```jinja2
-{% extends "shared/app_base.html" %}
-
-{% block title %}AppName - Description{% endblock %}
-
-{% set app_config = {
- 'slug': 'appname',
- 'name': 'AppName',
- 'description': 'Full description',
- 'entity_name': 'Item'
-} %}
-
-{% set app_tabs = [
- {'id': 'dashboard', 'label': 'Dashboard', 'icon': 'tachometer-alt'},
- // Add more tabs...
-] %}
-
-{% set stats = [
- {
- 'icon': 'icon-name',
- 'value': 'value',
- 'label': 'Label',
- 'color': '#hex',
- 'trend': number,
- 'trend_text': 'text'
- }
-] %}
-
-{% block dashboard_content %}
-
-{% endblock %}
-
-{% block additional_tabs %}
-
-{% endblock %}
-
-
-```
-
-### Step 3: Add Route (if needed)
-
-```python
-# src/ui/routes.py
-
-HEALTHCARE_APPS = {
- "appname": {
- "title": "AppName",
- "description": "Description",
- "status": "active"
- }
-}
-```
-
-## ๐ Migration Guide
-
-### Updating Existing Apps
-
-1. **Backup existing template**
-```bash
-cp apps/oldapp.html apps/oldapp_backup.html
-```
-
-2. **Create new template using modular system**
-```bash
-cp apps/surgio_new.html apps/newapp_new.html
-```
-
-3. **Customize for your app**
- - Update `app_config`
- - Define `app_tabs`
- - Set `stats` data
- - Add tab content
-
-4. **Test thoroughly**
- - Check all tabs switch correctly
- - Verify back button works
- - Test mobile responsiveness
- - Validate dark mode
-
-5. **Replace old template**
-```bash
-mv apps/newapp_new.html apps/newapp.html
-```
-
-## ๐ฏ Best Practices
-
-### โ
DO
-
-- Use the modular components
-- Follow the color scheme
-- Maintain consistent spacing
-- Add ARIA labels for accessibility
-- Test on mobile devices
-- Support dark mode
-- Use semantic HTML
-
-### โ DON'T
-
-- Hardcode styles inline (use classes)
-- Use emojis in production UI
-- Create custom layouts (use grid system)
-- Ignore mobile breakpoints
-- Skip error states
-- Forget loading states
-
-## ๐ฑ Responsive Design
-
-### Breakpoints
-
-```css
-/* Mobile First */
-@media (min-width: 640px) { /* sm */ }
-@media (min-width: 768px) { /* md */ }
-@media (min-width: 1024px) { /* lg */ }
-@media (min-width: 1280px) { /* xl */ }
-```
-
-### Mobile Optimizations
-
-- Back button shows icon only
-- Tab labels hidden (icons remain)
-- Stats grid stacks vertically
-- Actions buttons go full-width
-- Reduced padding/margins
-
-## ๐ Testing Checklist
-
-- [ ] All tabs switch correctly
-- [ ] Back to Home button works
-- [ ] Stats display properly
-- [ ] Mobile layout looks good
-- [ ] Dark mode works
-- [ ] Actions trigger correctly
-- [ ] No console errors
-- [ ] Browser tab title correct
-- [ ] Favicon loads
-- [ ] Performance acceptable
-
-## ๐ Examples
-
-See implemented examples:
-- `apps/surgio_new.html` - Complex dashboard with OR status
-- `apps/clinica_new.html` - Patient management
-- `apps/banko_new.html` - Financial with charts
-- `apps/movio_new.html` - Logistics tracking
-- `apps/insura_new.html` - Claims and risk
-
-## ๐ Future Enhancements
-
-- [ ] Add search functionality component
-- [ ] Create notification system component
-- [ ] Build data table component
-- [ ] Add form builder component
-- [ ] Create modal/dialog component
-- [ ] Build calendar component
-- [ ] Add file upload component
-
-## ๐ค Contributing
-
-When adding new components:
-1. Create in `components/` directory
-2. Document usage in this README
-3. Add examples
-4. Test across all apps
-5. Update migration guide
-
----
-
-**Version**: 1.0.0
-**Last Updated**: December 30, 2025
-**Maintainer**: YAZ Care Platform Team
diff --git a/docs/architecture/VALIDATION_TEST_RESULTS.md b/docs/architecture/VALIDATION_TEST_RESULTS.md
deleted file mode 100644
index 13edf632d295c91daeaa448b16bdb13e85034ce2..0000000000000000000000000000000000000000
--- a/docs/architecture/VALIDATION_TEST_RESULTS.md
+++ /dev/null
@@ -1,251 +0,0 @@
-# Validation Test Results - Sprint 34
-**Date**: December 28, 2025
-**Phase**: Codebase Creation Logic Revision & Validation Infrastructure
-
-## Summary
-Successfully created and tested comprehensive codebase creation infrastructure with automated tool generation and validation scripts.
-
----
-
-## 1. Tool Generator Test Results
-
-### Test Case: Create Test Medical Tool
-```bash
-python3 scripts/generators/create_tool.py \
- --name testmed \
- --display-name "TestMed (Test Medical Tool)" \
- --category clinical \
- --standards "HL7 FHIR,HIPAA" \
- --description "Test medical tool for workflow validation"
-```
-
-### Result: โ
SUCCESS
-**Files Created** (9 files):
-- โ
`src/apps/testmed/__init__.py` - Module initialization with router export
-- โ
`src/apps/testmed/models.py` - Domain models (SQLModel + TenantMixin)
-- โ
`src/apps/testmed/schemas.py` - API schemas (Pydantic V2)
-- โ
`src/apps/testmed/routes.py` - FastAPI endpoints
-- โ
`src/apps/testmed/services/testmed_service.py` - Business logic
-- โ
`src/apps/testmed/services/__init__.py` - Service module init
-- โ
`src/apps/testmed/adapters/__init__.py` - Event-driven wrappers
-- โ
`src/apps/testmed/events/__init__.py` - Domain events
-- โ
`tests/apps/testmed/__init__.py` - Test module initialization
-
-**Time to Generate**: <2 seconds
-**Manual Effort Saved**: ~4-6 hours (estimated)
-
----
-
-## 2. Structure Validation Test Results
-
-### Test Case 1: Newly Created Tool (testmed)
-```bash
-python3 scripts/validation/check_structure.py --tool testmed
-```
-
-### Result: โ
PASSED (with warnings)
-**Successes** (9/12 checks):
-- โ
Tool directory exists: `src/apps/testmed/`
-- โ
`__init__.py` exists
-- โ
`models.py` exists
-- โ
`schemas.py` exists
-- โ
`routes.py` exists
-- โ
`services/` directory exists
-- โ
`adapters/` directory exists
-- โ
`events/` directory exists
-- โ
Router properly exported from `__init__.py`
-- โ
Test directory exists: `tests/apps/testmed/`
-
-**Warnings** (3/12 recommended):
-- โ ๏ธ Recommended test file missing: `test_models.py`
-- โ ๏ธ Recommended test file missing: `test_services.py`
-- โ ๏ธ Recommended test file missing: `test_routes.py`
-
-**Analysis**: Generator creates directory structure correctly. Test files require manual implementation (expected behavior).
-
----
-
-### Test Case 2: Existing Tool (surgio)
-```bash
-python3 scripts/validation/check_structure.py --tool surgio
-```
-
-### Result: โ FAILED (3 errors) - Expected Behavior
-**Successes** (6/12 checks):
-- โ
Tool directory exists: `src/apps/surgio/`
-- โ
`__init__.py` exists
-- โ
`services/` directory exists
-- โ
`adapters/` directory exists
-- โ
Router properly exported from `__init__.py`
-- โ
Test directory exists: `tests/apps/surgio/`
-
-**Warnings** (4/12 recommended):
-- โ ๏ธ Recommended directory missing: `events/`
-- โ ๏ธ Recommended test file missing: `test_models.py`
-- โ ๏ธ Recommended test file missing: `test_services.py`
-- โ ๏ธ Recommended test file missing: `test_routes.py`
-
-**Errors** (3/12 required):
-- โ Required file missing: `models.py`
-- โ Required file missing: `schemas.py`
-- โ Required file missing: `routes.py`
-
-**Actual Structure** (surgio uses different naming):
-- Uses `router.py` instead of `routes.py` โ
-- Uses `domain/` directory instead of `models.py` โ
-- Uses `api.py`, `api_analytics.py`, `api_schedule.py`, `api_standards.py` โ
-
-**Analysis**: Validation correctly identified non-standard structure. Surgio predates new standards (legacy structure). This is **expected behavior** - the validator enforces new standards while identifying legacy tools that need refactoring.
-
----
-
-## 3. Governance Validation Test Results
-
-### Test Case: Check Tool Registration
-```bash
-python3 scripts/validation/check_governance.py --tool testmed
-```
-
-### Result: โ BLOCKED - Missing Models
-**Error**:
-```
-ImportError: cannot import name 'Tool' from 'core.database.governance'
-```
-
-**Root Cause**: `Tool` and `SystemTool` models not yet defined in `core/database/governance.py`
-
-**Current Governance Models** (in `core/database/governance.py`):
-- โ
`LegalEntity` - Ownership layer (VAVA, YEMA, AYUJI)
-- โ
`System` - Operational layer (YAZ, AYRAD, AZUL)
-- โ
`Tenant` - Customer workspace layer
-- โ
`User` - Individual user layer
-- โ `Tool` - **MISSING** (software product layer)
-- โ `SystemTool` - **MISSING** (system-tool association)
-
-**Action Required**: Create `Tool` and `SystemTool` models in governance layer before governance validation can run.
-
----
-
-## 4. Impact Analysis
-
-### Time Savings (Per Tool Creation)
-| Task | Manual Time | Automated Time | Savings |
-|------|-------------|----------------|---------|
-| Create directory structure | 5 min | 0 sec | 5 min |
-| Create `models.py` template | 30 min | 0 sec | 30 min |
-| Create `schemas.py` template | 30 min | 0 sec | 30 min |
-| Create `routes.py` template | 20 min | 0 sec | 20 min |
-| Create `services/` template | 45 min | 0 sec | 45 min |
-| Create `adapters/` template | 30 min | 0 sec | 30 min |
-| Create `events/` template | 20 min | 0 sec | 20 min |
-| Create `tests/` stubs | 15 min | 0 sec | 15 min |
-| Add multi-tenancy boilerplate | 30 min | 0 sec | 30 min |
-| Add clinical standards docs | 20 min | 0 sec | 20 min |
-| **TOTAL** | **~4 hours** | **<2 seconds** | **~240 min (88% reduction)** |
-
-### Code Quality Improvements
-- โ
**100% consistency** - All tools follow identical patterns
-- โ
**Zero boilerplate errors** - Templates are pre-validated
-- โ
**Multi-tenancy by default** - TenantMixin automatically included
-- โ
**Clinical standards enforced** - Documentation templates mandatory
-- โ
**Event-driven ready** - Publisher/adapter scaffolding included
-- โ
**Test structure standardized** - Test directories created upfront
-
----
-
-## 5. Validation Scripts Status
-
-| Script | Status | Purpose | Dependencies |
-|--------|--------|---------|--------------|
-| `check_structure.py` | โ
TESTED | Validate file structure (15 checks) | None - filesystem only |
-| `check_governance.py` | โธ๏ธ BLOCKED | Validate governance registration (10 checks) | Needs `Tool` model |
-| `check_performance.py` | โณ PENDING | Validate performance targets (<200ms p95) | Requires running app |
-| `check_security.py` | โณ PENDING | Validate security (tenant isolation, RBAC) | Requires database |
-| `check_coverage.py` | โณ PENDING | Validate test coverage (85%+) | Requires pytest run |
-
----
-
-## 6. Next Steps
-
-### Immediate (Sprint 34 Completion)
-1. **Create Tool Models** (HIGH PRIORITY):
- - Add `Tool` model to `core/database/governance.py`
- - Add `SystemTool` association model
- - Create Alembic migration for new tables
- - Update validation scripts to use new models
-
-2. **Test Remaining Validation Scripts**:
- - Run `check_performance.py` against testmed (requires app running)
- - Run `check_security.py` against testmed (requires database)
- - Run `check_coverage.py` against testmed (requires tests)
-
-3. **CI/CD Integration**:
- - Add validation scripts to GitHub Actions (`.github/workflows/validation.yml`)
- - Add pre-commit hooks (`.pre-commit-config.yaml`)
- - Configure automatic validation on PR creation
-
-### Short-Term (Next Sprint)
-4. **Legacy Tool Refactoring**:
- - Identify tools with non-standard structure (like surgio)
- - Create migration guide from old โ new structure
- - Refactor 1-2 tools per sprint to new standards
-
-5. **Documentation Enhancement**:
- - Add validation script examples to developer guide
- - Document common validation failures and fixes
- - Create troubleshooting guide for validation errors
-
-6. **Tool Registry Dashboard**:
- - Create admin UI to view all registered tools
- - Show validation status per tool (โ
/โ ๏ธ/โ)
- - Display governance alignment metrics
-
----
-
-## 7. Lessons Learned
-
-### What Worked Well
-- โ
**Generator script** - Extremely fast (<2s), 100% reliable
-- โ
**Structure validation** - Correctly identifies standard vs. legacy tools
-- โ
**Template quality** - Generated code follows all best practices
-- โ
**Documentation** - Templates include clinical context automatically
-
-### Challenges Encountered
-- โ ๏ธ **Missing governance models** - Tool/SystemTool not in database schema yet
-- โ ๏ธ **Legacy tool compatibility** - Existing tools use different naming conventions
-- โ ๏ธ **Validation dependency chain** - Some scripts require app/DB to be running
-
-### Recommendations
-1. **Prioritize Tool model creation** - Governance validation blocked without it
-2. **Create migration scripts** - Help legacy tools adopt new standards gradually
-3. **Add validation to CI/CD** - Catch violations before merge
-4. **Document exceptions** - Some tools may have valid reasons for non-standard structure
-
----
-
-## 8. Conclusion
-
-### Summary
-The codebase creation logic revision was **highly successful**:
-- โ
Generator creates tools in <2 seconds (88% time reduction)
-- โ
Structure validation works correctly (identifies standard vs. legacy)
-- โ
Templates enforce multi-tenancy, security, clinical standards
-- โธ๏ธ Governance validation blocked pending Tool model creation
-- โณ Performance/security/coverage validation pending integration testing
-
-### Next Milestone
-**Complete governance model creation** to unblock full validation pipeline, then integrate all 5 validation scripts into CI/CD for automatic enforcement.
-
-### Success Metrics (Achieved)
-- โ
**Reproducibility**: Generator creates identical structure every time
-- โ
**Modularity**: Self-contained apps/tools with clear boundaries
-- โ
**Future-Proofing**: BaseService inheritance for automatic improvements
-- โ
**Scalability**: Event-driven, multi-tenant architecture by default
-
-**Status**: ๐ข **SPRINT 34 CODEBASE CREATION OBJECTIVE ACHIEVED**
-
----
-
-**Report Generated**: December 28, 2025
-**Sprint**: 34 of 52 (97% complete, 7 days ahead of schedule)
-**Next Review**: Sprint 35 (January 2026)
diff --git a/scripts/validation/validate_ui_ux.py b/scripts/validation/validate_ui_ux.py
new file mode 100755
index 0000000000000000000000000000000000000000..0af0ab87170db37ea3626129063167ee10e35eda
--- /dev/null
+++ b/scripts/validation/validate_ui_ux.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env python3
+"""
+UI/UX Coherency Validation Script
+
+Validates that all app templates follow the standardized design patterns.
+"""
+
+import os
+import re
+from pathlib import Path
+from typing import List, Dict, Tuple
+
+# Define expected patterns
+REQUIRED_PATTERNS = {
+ 'extends_app_base': r'{%extends\s+"shared/app_base\.html"\s*%}',
+ 'app_config': r'{%set\s+app_config\s*=\s*{',
+ 'app_tabs': r'{%set\s+app_tabs\s*=\s*\[',
+ 'stats': r'{%set\s+stats\s*=\s*\[',
+ 'dashboard_content': r'{%block\s+dashboard_content\s*%}',
+ 'additional_tabs': r'{%block\s+additional_tabs\s*%}',
+ 'app_scripts': r'{%block\s+app_scripts\s*%}',
+ 'dark_mode': r'dark:bg-gray-',
+ 'aria_labels': r'aria-(label|hidden)',
+ 'htmx_integration': r'hx-(get|trigger|target)',
+}
+
+APPS_TO_CHECK = [
+ 'surgio', 'clinica', 'pharma', 'labo', 'educa', 'insura',
+ 'movio', 'banko', 'trena', 'campo', 'lodger', 'hospi',
+ 'stoka', 'fabrica'
+]
+
+def check_template(filepath: Path) -> Dict[str, bool]:
+ """Check if template follows all required patterns."""
+ with open(filepath, 'r', encoding='utf-8') as f:
+ content = f.read()
+
+ results = {}
+ for pattern_name, pattern in REQUIRED_PATTERNS.items():
+ results[pattern_name] = bool(re.search(pattern, content, re.MULTILINE))
+
+ return results
+
+def extract_gradient_colors(filepath: Path) -> Tuple[str, str]:
+ """Extract gradient colors from template."""
+ with open(filepath, 'r', encoding='utf-8') as f:
+ content = f.read()
+
+ from_match = re.search(r"'gradient_from':\s*'(#[0-9a-fA-F]{6})'", content)
+ to_match = re.search(r"'gradient_to':\s*'(#[0-9a-fA-F]{6})'", content)
+
+ gradient_from = from_match.group(1) if from_match else 'N/A'
+ gradient_to = to_match.group(1) if to_match else 'N/A'
+
+ return gradient_from, gradient_to
+
+def main():
+ """Main validation function."""
+ print("๐ YAZ Care Platform - UI/UX Coherency Validation")
+ print("=" * 70)
+ print()
+
+ templates_dir = Path('src/ui/templates/apps')
+
+ if not templates_dir.exists():
+ print(f"โ Templates directory not found: {templates_dir}")
+ return
+
+ all_passed = True
+ gradient_colors = {}
+
+ for app_name in APPS_TO_CHECK:
+ template_file = templates_dir / f"{app_name}.html"
+
+ if not template_file.exists():
+ print(f"โ ๏ธ {app_name}: Template not found")
+ continue
+
+ print(f"๐ Checking {app_name}...")
+
+ # Check patterns
+ results = check_template(template_file)
+ gradient_from, gradient_to = extract_gradient_colors(template_file)
+
+ gradient_colors[app_name] = (gradient_from, gradient_to)
+
+ # Count passes
+ passed = sum(1 for v in results.values() if v)
+ total = len(results)
+
+ if passed == total:
+ print(f" โ
All checks passed ({passed}/{total})")
+ print(f" ๐จ Gradient: {gradient_from} โ {gradient_to}")
+ else:
+ print(f" โ ๏ธ {passed}/{total} checks passed")
+ all_passed = False
+
+ # Show which checks failed
+ for pattern_name, passed in results.items():
+ if not passed:
+ print(f" โ Missing: {pattern_name}")
+
+ print()
+
+ # Check for gradient color conflicts
+ print("๐จ Gradient Color Uniqueness Check")
+ print("-" * 70)
+
+ color_usage = {}
+ for app_name, (gradient_from, gradient_to) in gradient_colors.items():
+ color_key = f"{gradient_from}โ{gradient_to}"
+ if color_key not in color_usage:
+ color_usage[color_key] = []
+ color_usage[color_key].append(app_name)
+
+ conflicts_found = False
+ for color_key, apps in color_usage.items():
+ if len(apps) > 1:
+ print(f"โ ๏ธ Color conflict: {color_key}")
+ print(f" Used by: {', '.join(apps)}")
+ conflicts_found = True
+ all_passed = False
+
+ if not conflicts_found:
+ print("โ
All apps have unique gradient colors")
+
+ print()
+ print("=" * 70)
+
+ if all_passed:
+ print("โ
All validations passed! UI/UX is coherent and homogeneous.")
+ return 0
+ else:
+ print("โ ๏ธ Some validations failed. Please review issues above.")
+ return 1
+
+if __name__ == '__main__':
+ exit(main())
diff --git a/src/apps/clinica/router.py b/src/apps/clinica/router.py
index 4555ab205b03e727f806768361f4817042f93ab1..c8fd076afb12284ede591b46619142fd219fcfeb 100644
--- a/src/apps/clinica/router.py
+++ b/src/apps/clinica/router.py
@@ -119,7 +119,7 @@ async def clinica_dashboard(request: Request, session: Session = Depends(get_db_
"nav_modules": get_nav_modules(),
}
- return templates.TemplateResponse("clinica/dashboard.html", context)
+ return templates.TemplateResponse("apps/clinica/dashboard.html", context)
# ============================================
diff --git a/src/apps/pharma/router.py b/src/apps/pharma/router.py
index 8155f51df091c53c054bee0bfd13af4fc995ca25..ceff5c503f7afb59b5a2f61bb7656c0f92fd6c22 100644
--- a/src/apps/pharma/router.py
+++ b/src/apps/pharma/router.py
@@ -54,4 +54,4 @@ async def pharma_dashboard(request: Request):
"recent_items": [{"title": "Last update", "time": "2 min ago"}],
"nav_modules": get_nav_modules(),
}
- return templates.TemplateResponse("pharma/dashboard.html", context)
+ return templates.TemplateResponse("apps/pharma/dashboard.html", context)
diff --git a/src/apps/platform/unified_dashboard.py b/src/apps/platform/unified_dashboard.py
index bd24adad2acd68a30a14a9b61824a2cbc185b891..fad3d7b2d9f56aacdc9af7d0249cecb4ede9be0f 100644
--- a/src/apps/platform/unified_dashboard.py
+++ b/src/apps/platform/unified_dashboard.py
@@ -132,21 +132,6 @@ HEALTHCARE_MODULES = [
{"label": "CME Tracking", "href": "/apps/educa/cme"}
]
),
- ModuleCard(
- slug="trena",
- display_name="Trena",
- icon="๐",
- category="Education & Training",
- description="Training Coordination & Certification",
- color="bg-orange-500",
- href="/apps/trena",
- quick_actions=[
- {"label": "Courses", "href": "/apps/trena/courses"},
- {"label": "Certifications", "href": "/apps/trena/certifications"},
- {"label": "Schedule", "href": "/apps/trena/schedule"},
- {"label": "Compliance", "href": "/apps/trena/compliance"}
- ]
- ),
# FINANCIAL MANAGEMENT - Revenue & Billing
ModuleCard(
diff --git a/src/apps/surgio/router.py b/src/apps/surgio/router.py
index d075a5758f8641ad5196410b739053d9876c8b1a..ca0b10e8b5b3909e99b59c9d2fc43568f726e0fc 100644
--- a/src/apps/surgio/router.py
+++ b/src/apps/surgio/router.py
@@ -191,10 +191,20 @@ async def surgio_dashboard(
import logging
logging.debug(f"Surgio dashboard: Database not ready, using mock data: {e}")
- return templates.TemplateResponse("surgio/dashboard.html", {
+ return templates.TemplateResponse("apps/surgio/dashboard.html", {
"request": request,
"app_name": "surgio",
"current_time": datetime.now(),
+ "total_count": total_today,
+ "active_count": active,
+ "completed_count": completed,
+ "success_rate": 98.5,
+ "trend": "+3",
+ "trend_text": "vs yesterday",
+ "active_trend": "+2",
+ "active_trend_text": "24h",
+ "completed_trend": "+5",
+ "completed_trend_text": "This week",
"dashboard_data": {
"case_metrics": {
"total_cases": total_today,
diff --git a/src/apps/trena/ROUTES_BOILERPLATE.py b/src/apps/trena/ROUTES_BOILERPLATE.py
deleted file mode 100644
index 404eb6e8437f6068dfbbe5465b6a80bb71069640..0000000000000000000000000000000000000000
--- a/src/apps/trena/ROUTES_BOILERPLATE.py
+++ /dev/null
@@ -1,258 +0,0 @@
-"""
-Trena - Open Source Routes
-Auto-generated UI/UX routes with CRUD operations
-
-Features:
-- List/Search with pagination
-- Create/Read/Update/Delete operations
-- Export (CSV, Excel, PDF)
-- Bulk import from CSV/Excel
-- Filtering and sorting
-"""
-
-from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile, File
-from fastapi.responses import StreamingResponse, HTMLResponse
-from typing import Optional, List
-from uuid import UUID
-import csv
-import io
-
-from src.auth.dependencies import get_current_user, verify_tenant_access
-from .schemas import (
- TrainingCreate,
- TrainingUpdate,
- TrainingResponse,
- TrainingList
-)
-from .service import TrenaService
-
-router = APIRouter(prefix="/apps/trena", tags=["Trena"])
-
-# ============================================================================
-# UI Routes (HTML responses)
-# ============================================================================
-
-@router.get("/", response_class=HTMLResponse)
-async def dashboard(
- tenant_id: str = Depends(verify_tenant_access),
- service: TrenaService = Depends()
-):
- """Main dashboard view"""
- stats = await service.get_statistics(tenant_id)
-
- from fastapi.templating import Jinja2Templates
- templates = Jinja2Templates(directory="src/ui/templates")
-
- return templates.TemplateResponse(
- "apps/trena_new.html",
- {
- "request": request,
- "stats": stats,
- "total_count": stats.get("total", 0),
- "active_count": stats.get("active", 0),
- "completed_count": stats.get("completed", 0),
- "success_rate": stats.get("success_rate", 0)
- }
- )
-
-@router.get("/table", response_class=HTMLResponse)
-async def get_table(
- page: int = Query(1, ge=1),
- page_size: int = Query(50, ge=1, le=1000),
- search: Optional[str] = Query(None),
- status: Optional[str] = Query(None),
- sort: str = Query("-created_at"),
- tenant_id: str = Depends(verify_tenant_access),
- service: TrenaService = Depends()
-):
- """Get table partial HTML"""
- items = await service.list(
- tenant_id=tenant_id,
- page=page,
- page_size=page_size,
- search=search,
- status=status,
- sort=sort
- )
-
- # Return HTML table partial
- # TODO: Create table template
- return "Table goes here
"
-
-# ============================================================================
-# API Routes (JSON responses)
-# ============================================================================
-
-@router.post("/items", response_model=TrainingResponse, status_code=201)
-async def create_item(
- data: TrainingCreate,
- current_user = Depends(get_current_user),
- tenant_id: str = Depends(verify_tenant_access),
- service: TrenaService = Depends()
-):
- """
- Create new training
-
- Clinical Context: Training Coordination
- Performance: <200ms target
- """
- return await service.create(data, tenant_id, current_user.id)
-
-@router.get("/items", response_model=TrainingList)
-async def list_items(
- page: int = Query(1, ge=1),
- page_size: int = Query(50, ge=1, le=1000),
- search: Optional[str] = Query(None),
- status: Optional[str] = Query(None),
- sort: str = Query("-created_at"),
- tenant_id: str = Depends(verify_tenant_access),
- service: TrenaService = Depends()
-):
- """
- List trainings with pagination
-
- Performance: <200ms target
- """
- return await service.list(
- tenant_id=tenant_id,
- page=page,
- page_size=page_size,
- search=search,
- status=status,
- sort=sort
- )
-
-@router.get("/items/{item_id}", response_model=TrainingResponse)
-async def get_item(
- item_id: UUID,
- tenant_id: str = Depends(verify_tenant_access),
- service: TrenaService = Depends()
-):
- """Get training by ID"""
- item = await service.get(item_id, tenant_id)
- if not item:
- raise HTTPException(status_code=404, detail="Training not found")
- return item
-
-@router.patch("/items/{item_id}", response_model=TrainingResponse)
-async def update_item(
- item_id: UUID,
- data: TrainingUpdate,
- current_user = Depends(get_current_user),
- tenant_id: str = Depends(verify_tenant_access),
- service: TrenaService = Depends()
-):
- """Update training"""
- item = await service.update(item_id, data, tenant_id, current_user.id)
- if not item:
- raise HTTPException(status_code=404, detail="Training not found")
- return item
-
-@router.delete("/items/{item_id}", status_code=204)
-async def delete_item(
- item_id: UUID,
- current_user = Depends(get_current_user),
- tenant_id: str = Depends(verify_tenant_access),
- service: TrenaService = Depends()
-):
- """Soft delete training"""
- success = await service.delete(item_id, tenant_id, current_user.id)
- if not success:
- raise HTTPException(status_code=404, detail="Training not found")
-
-# ============================================================================
-# Export Routes (Open Source)
-# ============================================================================
-
-@router.get("/export")
-async def export_items(
- format: str = Query("csv", regex="^(csv|xlsx|pdf)$"),
- tenant_id: str = Depends(verify_tenant_access),
- service: TrenaService = Depends()
-):
- """
- Export trainings in CSV, Excel, or PDF format
-
- Open Source Feature: Basic data export
- """
- items = await service.list(tenant_id=tenant_id, page_size=10000)
-
- if format == "csv":
- # Generate CSV
- output = io.StringIO()
- writer = csv.DictWriter(output, fieldnames=["id", "name", "status", "created_at"])
- writer.writeheader()
- for item in items.items:
- writer.writerow({
- "id": str(item.id),
- "name": item.name,
- "status": item.status,
- "created_at": item.created_at.isoformat()
- })
-
- return StreamingResponse(
- io.BytesIO(output.getvalue().encode()),
- media_type="text/csv",
- headers={"Content-Disposition": f"attachment; filename=trena_export.csv"}
- )
-
- elif format == "xlsx":
- # TODO: Implement Excel export with openpyxl
- raise HTTPException(status_code=501, detail="Excel export coming soon")
-
- elif format == "pdf":
- # TODO: Implement PDF export with reportlab
- raise HTTPException(status_code=501, detail="PDF export coming soon")
-
-@router.post("/import")
-async def import_items(
- file: UploadFile = File(...),
- current_user = Depends(get_current_user),
- tenant_id: str = Depends(verify_tenant_access),
- service: TrenaService = Depends()
-):
- """
- Bulk import trainings from CSV/Excel
-
- Open Source Feature: Bulk data import
- """
- # TODO: Implement CSV/Excel import
- # TODO: Validate data
- # TODO: Bulk create with transaction
- raise HTTPException(status_code=501, detail="Import feature coming soon")
-
-# ============================================================================
-# Analytics Routes (Placeholder for Proprietary)
-# ============================================================================
-
-@router.get("/analytics/advanced")
-async def get_advanced_analytics(
- tenant_id: str = Depends(verify_tenant_access)
-):
- """
- TODO: PROPRIETARY - Advanced AI-powered analytics
-
- Future Features:
- - Predictive modeling with ML
- - Automated insights generation
- - Trend forecasting
- - Anomaly detection
- - Optimization recommendations
-
- Dependencies:
- - AYRAD Fusion integration
- - ML model training pipeline
- - Real-time data streaming
-
- Estimated Effort: 2-3 weeks
- Priority: High
- """
- return {
- "message": "Advanced analytics coming soon",
- "features": [
- "Predictive modeling",
- "AI-driven insights",
- "Automated recommendations",
- "Real-time alerting"
- ]
- }
diff --git a/src/apps/trena/__init__.py b/src/apps/trena/__init__.py
deleted file mode 100644
index 609874062daa202ddcd45111261019fb1514c23a..0000000000000000000000000000000000000000
--- a/src/apps/trena/__init__.py
+++ /dev/null
@@ -1,12 +0,0 @@
-"""
-Trena - Training & Professional Development Application
-Healthcare professional training and development platform
-"""
-
-from .router import router
-
-__version__ = "1.0.0"
-__app_name__ = "trena"
-__description__ = "Healthcare professional training and development platform"
-
-__all__ = ["router"]
\ No newline at end of file
diff --git a/src/apps/trena/adapters/__init__.py b/src/apps/trena/adapters/__init__.py
deleted file mode 100644
index 1d30db448e61d39c48b4f948a5c61e8959885ef2..0000000000000000000000000000000000000000
--- a/src/apps/trena/adapters/__init__.py
+++ /dev/null
@@ -1,45 +0,0 @@
-"""
-Trena Adapters - Training Coordination & Development
-
-Event-driven integration layer for medical training, continuing education,
-competency assessment, and professional development programs.
-
-This adapter provides:
-- Training program events (course enrollment, completion, certification)
-- Competency assessment events (skill evaluation, milestone tracking)
-- Continuing education events (CME/CE credits, license renewal)
-- Clinical training events (residency, fellowship, preceptorship)
-- Simulation training events (scenario execution, performance analysis)
-- Instructor management events (faculty assignments, evaluations)
-
-Healthcare Context:
-- ACGME residency and fellowship training programs
-- Continuing Medical Education (CME) compliance
-- Nursing continuing education (CE) requirements
-- Competency-based medical education (CBME)
-- Simulation-based training and assessment
-- Professional license maintenance
-
-Pattern: Full adapter layer (events + repository + enhanced service)
-Enables competency tracking, credential management, training analytics,
-and automated compliance monitoring.
-
-Standards:
-- Medical Education: ACGME Milestones 2.0, ABMS MOC
-- Nursing Education: ANCC accreditation standards
-- CME: ACCME accreditation criteria
-- Simulation: SSH Certification Standards
-- Competency: ACGME Core Competencies, EPA framework
-"""
-
-from .event_publisher import TrenaEventPublisher, TrenaEventType, TrenaEvent
-from .repository_adapter import TrenaRepositoryAdapter
-from .enhanced_service import EnhancedTrenaService
-
-__all__ = [
- "TrenaEventPublisher",
- "TrenaEventType",
- "TrenaEvent",
- "TrenaRepositoryAdapter",
- "EnhancedTrenaService",
-]
diff --git a/src/apps/trena/adapters/enhanced_service.py b/src/apps/trena/adapters/enhanced_service.py
deleted file mode 100644
index ac15ee6132f280b18d1ac6fcdbc1482706c87baf..0000000000000000000000000000000000000000
--- a/src/apps/trena/adapters/enhanced_service.py
+++ /dev/null
@@ -1,96 +0,0 @@
-"""
-Enhanced Trena Service - Training & Education Intelligence
-
-Enhanced service layer providing AI-driven insights for medical training,
-competency assessment, and professional development.
-
-Features:
-- Learning path optimization (personalized training recommendations)
-- Competency gap analysis (skill deficiency identification)
-- Graduation readiness prediction (milestone-based assessment)
-- CME/CE compliance monitoring (automated tracking)
-- Simulation performance analytics (skill improvement tracking)
-
-Healthcare Context:
-- ACGME-compliant training program management
-- Professional credential maintenance
-- Competency-based medical education
-- Clinical skills development tracking
-
-Performance: <200ms for analytics queries
-"""
-
-from typing import Dict, Any, Optional
-from datetime import datetime, timedelta
-import structlog
-
-from .repository_adapter import TrenaRepositoryAdapter
-from .event_publisher import TrenaEventPublisher
-
-logger = structlog.get_logger()
-
-
-class EnhancedTrenaService:
- """
- Enhanced trena service with AI-driven training intelligence.
-
- Healthcare Impact:
- - 30% faster competency achievement
- - 95%+ license renewal compliance
- - Personalized learning recommendations
- - Early identification of struggling learners
- """
-
- def __init__(
- self,
- repository_adapter: TrenaRepositoryAdapter,
- event_publisher: Optional[TrenaEventPublisher] = None
- ):
- """Initialize enhanced trena service."""
- self.repository = repository_adapter
- self.event_publisher = event_publisher or TrenaEventPublisher()
- self.logger = structlog.get_logger()
-
- async def analyze_competency_gaps(
- self,
- tenant_id: str,
- user_id: str,
- trainee_id: str
- ) -> Dict[str, Any]:
- """
- Analyze competency gaps and recommend training.
-
- Healthcare Impact:
- - Targeted remediation planning
- - Individualized learning paths
- - Improved graduation readiness
- """
- start_time = datetime.utcnow()
-
- # Competency gap analysis
- analysis = {
- "trainee_id": trainee_id,
- "competency_gaps": [
- {"domain": "medical_knowledge", "current_level": 2, "target_level": 4, "gap": 2},
- {"domain": "patient_care", "current_level": 3, "target_level": 4, "gap": 1}
- ],
- "recommendations": [
- "Complete advanced pharmacology course",
- "Increase clinical exposure in ICU rotation"
- ],
- "graduation_readiness": 0.65,
- "estimated_weeks_to_graduation": 26
- }
-
- duration_ms = (datetime.utcnow() - start_time).total_seconds() * 1000
-
- self.logger.info(
- "competency_gaps_analyzed",
- tenant_id=tenant_id,
- trainee_id=trainee_id,
- gap_count=len(analysis["competency_gaps"]),
- graduation_readiness=0.65,
- duration_ms=duration_ms
- )
-
- return analysis
diff --git a/src/apps/trena/adapters/event_publisher.py b/src/apps/trena/adapters/event_publisher.py
deleted file mode 100644
index b71093aba087b884096cc553e66de9ab9927d4f2..0000000000000000000000000000000000000000
--- a/src/apps/trena/adapters/event_publisher.py
+++ /dev/null
@@ -1,462 +0,0 @@
-"""
-Trena Event Publisher - Training & Education Events
-
-Publishes domain events for medical training, continuing education,
-competency assessment, and professional development activities.
-
-Healthcare Context:
-- Medical residency and fellowship training programs
-- Continuing Medical Education (CME) and CE compliance
-- Competency-based education and milestone tracking
-- Clinical skills training and simulation
-- Professional credential management
-- Faculty development and teaching effectiveness
-
-Performance: <100ms event publishing, real-time competency tracking
-"""
-
-from dataclasses import dataclass, field
-from datetime import datetime
-from enum import Enum
-from typing import Dict, Any, Optional, List
-from uuid import uuid4
-import structlog
-
-logger = structlog.get_logger()
-
-
-class TrenaEventType(str, Enum):
- """Trena domain event types."""
-
- # Training Program Events
- PROGRAM_ENROLLMENT = "program_enrollment"
- COURSE_STARTED = "course_started"
- COURSE_COMPLETED = "course_completed"
- PROGRAM_GRADUATION = "program_graduation"
-
- # Competency Assessment Events
- COMPETENCY_EVALUATED = "competency_evaluated"
- MILESTONE_ACHIEVED = "milestone_achieved"
- SKILL_ASSESSMENT_COMPLETED = "skill_assessment_completed"
- REMEDIATION_REQUIRED = "remediation_required"
-
- # CME/CE Events
- CME_CREDITS_EARNED = "cme_credits_earned"
- CE_ACTIVITY_COMPLETED = "ce_activity_completed"
- LICENSE_RENEWAL_DUE = "license_renewal_due"
- CERTIFICATION_EXPIRING = "certification_expiring"
-
- # Clinical Training Events
- CLINICAL_ROTATION_STARTED = "clinical_rotation_started"
- CLINICAL_ROTATION_COMPLETED = "clinical_rotation_completed"
- CASE_LOG_SUBMITTED = "case_log_submitted"
- PROCEDURE_LOGGED = "procedure_logged"
-
- # Simulation Training Events
- SIMULATION_SESSION_STARTED = "simulation_session_started"
- SIMULATION_COMPLETED = "simulation_completed"
- SIMULATION_DEBRIEFING = "simulation_debriefing"
-
- # Instructor Events
- INSTRUCTOR_ASSIGNED = "instructor_assigned"
- EVALUATION_SUBMITTED = "evaluation_submitted"
- TEACHING_SESSION_COMPLETED = "teaching_session_completed"
-
-
-@dataclass
-class TrenaEvent:
- """Trena domain event."""
- event_id: str = field(default_factory=lambda: str(uuid4()))
- event_type: TrenaEventType = TrenaEventType.COURSE_STARTED
- tenant_id: str = ""
- user_id: str = ""
- timestamp: datetime = field(default_factory=datetime.utcnow)
- metadata: Dict[str, Any] = field(default_factory=dict)
-
-
-class TrenaEventPublisher:
- """
- Publishes trena domain events for training and education.
-
- Healthcare Context:
- - ACGME-compliant residency/fellowship training tracking
- - CME/CE credit management for license maintenance
- - Competency-based education with milestone assessment
- - Clinical skills training and simulation
- - Professional development and credentialing
-
- Performance: <100ms publish latency, real-time tracking
- """
-
- def __init__(self):
- """Initialize trena event publisher."""
- self.logger = structlog.get_logger()
-
- async def publish_course_completed(
- self,
- tenant_id: str,
- user_id: str,
- course_id: str,
- learner_id: str,
- course_title: str,
- completion_date: datetime,
- final_score: float,
- cme_credits: float = 0.0,
- passed: bool = True,
- metadata: Optional[Dict[str, Any]] = None
- ) -> TrenaEvent:
- """
- Publish course completion event.
-
- Clinical Context: Track educational activity completion for CME/CE
- compliance, credential maintenance, and competency development.
-
- Standards: ACCME CME criteria, ANCC CE standards
-
- Healthcare Impact:
- - Automated CME/CE credit tracking
- - License renewal compliance monitoring
- - Competency progression documentation
- - Board certification maintenance
-
- Args:
- tenant_id: Multi-tenant isolation key
- user_id: System user
- course_id: Course identifier
- learner_id: Healthcare professional completing course
- course_title: Course name
- completion_date: Date of completion
- final_score: Assessment score (0-100)
- cme_credits: CME/CE credits awarded
- passed: Passing status
- metadata: Additional context
-
- Returns:
- Published trena event
- """
- event = TrenaEvent(
- event_type=TrenaEventType.COURSE_COMPLETED,
- tenant_id=tenant_id,
- user_id=user_id,
- metadata={
- "course_id": course_id,
- "learner_id": learner_id,
- "course_title": course_title,
- "completion_date": completion_date.isoformat(),
- "final_score": final_score,
- "cme_credits": cme_credits,
- "passed": passed,
- "certificate_issued": passed,
- "status": "completed",
- **(metadata or {})
- }
- )
-
- self.logger.info(
- "course_completed",
- event_id=event.event_id,
- tenant_id=tenant_id,
- learner_id=learner_id,
- course_title=course_title,
- final_score=final_score,
- cme_credits=cme_credits
- )
-
- return event
-
- async def publish_milestone_achieved(
- self,
- tenant_id: str,
- user_id: str,
- milestone_id: str,
- trainee_id: str,
- competency_domain: str,
- milestone_level: int,
- achievement_date: datetime,
- evaluator_id: str,
- metadata: Optional[Dict[str, Any]] = None
- ) -> TrenaEvent:
- """
- Publish milestone achievement event.
-
- Clinical Context: ACGME Milestones 2.0 framework for residency
- training. Track competency progression across six core domains
- with levels 1-5 representing novice to expert performance.
-
- Standards: ACGME Milestones 2.0, ABMS Core Competencies
-
- Healthcare Impact:
- - Competency-based progression tracking
- - Graduation readiness assessment
- - Individualized learning plans
- - Program evaluation and improvement
-
- Args:
- tenant_id: Multi-tenant isolation key
- user_id: System user
- milestone_id: Milestone identifier
- trainee_id: Resident/fellow identifier
- competency_domain: ACGME domain (patient care, medical knowledge, etc.)
- milestone_level: Level achieved (1-5)
- achievement_date: Date milestone was achieved
- evaluator_id: Faculty evaluator
- metadata: Additional context
-
- Returns:
- Published trena event
- """
- event = TrenaEvent(
- event_type=TrenaEventType.MILESTONE_ACHIEVED,
- tenant_id=tenant_id,
- user_id=user_id,
- metadata={
- "milestone_id": milestone_id,
- "trainee_id": trainee_id,
- "competency_domain": competency_domain,
- "milestone_level": milestone_level,
- "achievement_date": achievement_date.isoformat(),
- "evaluator_id": evaluator_id,
- "graduation_ready": milestone_level >= 4,
- "requires_improvement": milestone_level < 2,
- "status": "achieved",
- **(metadata or {})
- }
- )
-
- self.logger.info(
- "milestone_achieved",
- event_id=event.event_id,
- tenant_id=tenant_id,
- trainee_id=trainee_id,
- competency_domain=competency_domain,
- milestone_level=milestone_level,
- graduation_ready=milestone_level >= 4
- )
-
- return event
-
- async def publish_simulation_completed(
- self,
- tenant_id: str,
- user_id: str,
- simulation_id: str,
- participant_ids: List[str],
- scenario_type: str,
- performance_scores: Dict[str, float],
- duration_minutes: int,
- facilitator_id: str,
- metadata: Optional[Dict[str, Any]] = None
- ) -> TrenaEvent:
- """
- Publish simulation training completion event.
-
- Clinical Context: High-fidelity simulation training for critical
- clinical scenarios (codes, trauma, difficult airways). Track
- performance, teamwork, and decision-making skills.
-
- Standards: SSH Certification Standards, AHA simulation guidelines
-
- Healthcare Impact:
- - Safe practice of high-risk procedures
- - Team training and communication
- - Crisis resource management skills
- - Improved patient safety outcomes (20-30%)
-
- Args:
- tenant_id: Multi-tenant isolation key
- user_id: System user
- simulation_id: Simulation session identifier
- participant_ids: Participants in simulation
- scenario_type: Scenario (code blue, trauma, sepsis, etc.)
- performance_scores: Participant performance metrics
- duration_minutes: Simulation duration
- facilitator_id: Simulation instructor
- metadata: Additional context
-
- Returns:
- Published trena event
- """
- avg_score = sum(performance_scores.values()) / len(performance_scores) if performance_scores else 0
-
- event = TrenaEvent(
- event_type=TrenaEventType.SIMULATION_COMPLETED,
- tenant_id=tenant_id,
- user_id=user_id,
- metadata={
- "simulation_id": simulation_id,
- "participant_ids": participant_ids,
- "participant_count": len(participant_ids),
- "scenario_type": scenario_type,
- "performance_scores": performance_scores,
- "average_performance_score": avg_score,
- "duration_minutes": duration_minutes,
- "facilitator_id": facilitator_id,
- "debriefing_required": True,
- "status": "completed",
- **(metadata or {})
- }
- )
-
- self.logger.info(
- "simulation_completed",
- event_id=event.event_id,
- tenant_id=tenant_id,
- simulation_id=simulation_id,
- scenario_type=scenario_type,
- participant_count=len(participant_ids),
- average_score=avg_score
- )
-
- return event
-
- async def publish_license_renewal_due(
- self,
- tenant_id: str,
- user_id: str,
- professional_id: str,
- license_type: str,
- expiration_date: datetime,
- days_until_expiration: int,
- required_cme_credits: float,
- current_cme_credits: float,
- metadata: Optional[Dict[str, Any]] = None
- ) -> TrenaEvent:
- """
- Publish license renewal due notification event.
-
- Clinical Context: Professional license maintenance requires
- continuing education credits, timely renewal, and compliance
- documentation. Automated tracking prevents lapses.
-
- Healthcare Impact:
- - Prevention of license lapses (100% compliance)
- - Automated renewal reminders (60/30/14 days)
- - CME credit deficit tracking
- - Regulatory compliance assurance
-
- Args:
- tenant_id: Multi-tenant isolation key
- user_id: System user
- professional_id: Healthcare professional identifier
- license_type: License type (medical, nursing, pharmacy, etc.)
- expiration_date: License expiration date
- days_until_expiration: Days remaining
- required_cme_credits: Credits required for renewal
- current_cme_credits: Credits earned to date
- metadata: Additional context
-
- Returns:
- Published trena event
- """
- credit_deficit = max(0, required_cme_credits - current_cme_credits)
-
- event = TrenaEvent(
- event_type=TrenaEventType.LICENSE_RENEWAL_DUE,
- tenant_id=tenant_id,
- user_id=user_id,
- metadata={
- "professional_id": professional_id,
- "license_type": license_type,
- "expiration_date": expiration_date.isoformat(),
- "days_until_expiration": days_until_expiration,
- "required_cme_credits": required_cme_credits,
- "current_cme_credits": current_cme_credits,
- "credit_deficit": credit_deficit,
- "renewal_eligible": credit_deficit == 0,
- "urgency": "critical" if days_until_expiration <= 14 else "high" if days_until_expiration <= 30 else "medium",
- "status": "pending",
- **(metadata or {})
- }
- )
-
- log_method = self.logger.warning if days_until_expiration <= 30 else self.logger.info
- log_method(
- "license_renewal_due",
- event_id=event.event_id,
- tenant_id=tenant_id,
- professional_id=professional_id,
- license_type=license_type,
- days_until_expiration=days_until_expiration,
- credit_deficit=credit_deficit
- )
-
- return event
-
- async def publish_clinical_rotation_completed(
- self,
- tenant_id: str,
- user_id: str,
- rotation_id: str,
- trainee_id: str,
- rotation_type: str,
- specialty: str,
- start_date: datetime,
- end_date: datetime,
- supervisor_evaluation: Dict[str, Any],
- cases_logged: int,
- metadata: Optional[Dict[str, Any]] = None
- ) -> TrenaEvent:
- """
- Publish clinical rotation completion event.
-
- Clinical Context: Residency/fellowship clinical rotations across
- specialties. Track case volumes, competency development, and
- supervisor evaluations per ACGME requirements.
-
- Standards: ACGME program requirements, specialty-specific minimums
-
- Healthcare Impact:
- - Competency documentation
- - Case log tracking (ACGME minimums)
- - Multi-source evaluation data
- - Program compliance monitoring
-
- Args:
- tenant_id: Multi-tenant isolation key
- user_id: System user
- rotation_id: Rotation identifier
- trainee_id: Resident/fellow identifier
- rotation_type: Type (inpatient, outpatient, ICU, etc.)
- specialty: Clinical specialty
- start_date: Rotation start date
- end_date: Rotation end date
- supervisor_evaluation: Faculty evaluation scores
- cases_logged: Number of cases documented
- metadata: Additional context
-
- Returns:
- Published trena event
- """
- duration_weeks = (end_date - start_date).days // 7
-
- event = TrenaEvent(
- event_type=TrenaEventType.CLINICAL_ROTATION_COMPLETED,
- tenant_id=tenant_id,
- user_id=user_id,
- metadata={
- "rotation_id": rotation_id,
- "trainee_id": trainee_id,
- "rotation_type": rotation_type,
- "specialty": specialty,
- "start_date": start_date.isoformat(),
- "end_date": end_date.isoformat(),
- "duration_weeks": duration_weeks,
- "supervisor_evaluation": supervisor_evaluation,
- "cases_logged": cases_logged,
- "meets_minimum_cases": cases_logged >= 20, # Simplified threshold
- "status": "completed",
- **(metadata or {})
- }
- )
-
- self.logger.info(
- "clinical_rotation_completed",
- event_id=event.event_id,
- tenant_id=tenant_id,
- trainee_id=trainee_id,
- specialty=specialty,
- duration_weeks=duration_weeks,
- cases_logged=cases_logged
- )
-
- return event
diff --git a/src/apps/trena/adapters/repository_adapter.py b/src/apps/trena/adapters/repository_adapter.py
deleted file mode 100644
index f82e8b47d2d6ee80e7a7f45f6c5be226e320728b..0000000000000000000000000000000000000000
--- a/src/apps/trena/adapters/repository_adapter.py
+++ /dev/null
@@ -1,92 +0,0 @@
-"""
-Trena Repository Adapter - Training Data Layer
-
-Repository adapter with event publishing for training and education operations.
-Wraps existing TrenaRepository with event-driven capabilities.
-
-Performance: <50ms database operations, event publishing adds <10ms overhead
-"""
-
-from typing import Dict, Any, Optional
-from datetime import datetime
-import structlog
-
-from .event_publisher import TrenaEventPublisher
-
-logger = structlog.get_logger()
-
-
-class TrenaRepositoryAdapter:
- """
- Repository adapter for trena operations with event publishing.
-
- Wraps existing repository methods and publishes events for:
- - Training program enrollment and completion
- - Competency assessment and milestone tracking
- - CME/CE credit management
- - Clinical rotation documentation
- - Simulation training activities
-
- Pattern: Repository + Event Publisher (non-breaking enhancement)
- """
-
- def __init__(
- self,
- base_repository: Any,
- event_publisher: Optional[TrenaEventPublisher] = None
- ):
- """Initialize repository adapter."""
- self.repository = base_repository
- self.event_publisher = event_publisher or TrenaEventPublisher()
- self.logger = structlog.get_logger()
-
- async def complete_course(
- self,
- tenant_id: str,
- user_id: str,
- course_data: Dict[str, Any]
- ) -> Dict[str, Any]:
- """Complete course with event publishing."""
- completion = await self.repository.record_course_completion(
- tenant_id=tenant_id,
- course_data=course_data
- )
-
- await self.event_publisher.publish_course_completed(
- tenant_id=tenant_id,
- user_id=user_id,
- course_id=course_data.get("course_id", ""),
- learner_id=course_data.get("learner_id", ""),
- course_title=course_data.get("course_title", ""),
- completion_date=datetime.fromisoformat(course_data.get("completion_date")),
- final_score=course_data.get("final_score", 0.0),
- cme_credits=course_data.get("cme_credits", 0.0),
- passed=course_data.get("passed", True)
- )
-
- return completion
-
- async def record_milestone(
- self,
- tenant_id: str,
- user_id: str,
- milestone_data: Dict[str, Any]
- ) -> Dict[str, Any]:
- """Record milestone achievement with event publishing."""
- milestone = await self.repository.create_milestone(
- tenant_id=tenant_id,
- milestone_data=milestone_data
- )
-
- await self.event_publisher.publish_milestone_achieved(
- tenant_id=tenant_id,
- user_id=user_id,
- milestone_id=milestone.get("id"),
- trainee_id=milestone_data.get("trainee_id", ""),
- competency_domain=milestone_data.get("competency_domain", ""),
- milestone_level=milestone_data.get("milestone_level", 1),
- achievement_date=datetime.fromisoformat(milestone_data.get("achievement_date")),
- evaluator_id=milestone_data.get("evaluator_id", "")
- )
-
- return milestone
diff --git a/src/apps/trena/api.py b/src/apps/trena/api.py
deleted file mode 100644
index e1998d684b55d4ed47eb4e1e9a17fa5f22196ade..0000000000000000000000000000000000000000
--- a/src/apps/trena/api.py
+++ /dev/null
@@ -1,686 +0,0 @@
-"""
-YAZ Care Platform - Trena API
-Comprehensive Training Management & Skill Assessment API
-Advanced training intelligence, skill development, and performance analytics
-"""
-
-from fastapi import APIRouter, Request, Depends, HTTPException, Query, Body
-from fastapi.responses import HTMLResponse, JSONResponse
-from fastapi.templating import Jinja2Templates
-from pathlib import Path
-from typing import Dict, List, Any, Optional
-from datetime import datetime, timedelta
-from decimal import Decimal
-import json
-
-from core.api.dependencies import require_user_context, get_configured_service_factory
-from core.api.auth import require_admin_or_manager, require_authenticated_user
-from core.common.exceptions import ValidationException, TrainingException
-
-from .service import (
- trena_service,
- TrainingCriteria,
- TrainingAlternative,
- SkillAssessment,
- TrainingProgram,
- TrainingType,
- SkillLevel,
- TrainingPriority,
- AssessmentMethod
-)
-
-# Configure templates
-TEMPLATES_DIR = Path(__file__).parent.parent.parent / "src" / "ui" / "templates"
-templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
-
-# Main dashboard router
-router = APIRouter(prefix="/trena", tags=["trena"])
-
-# API endpoints router
-trena_api_router = APIRouter(prefix="/api/v1/trena", tags=["trena-api"])
-
-
-# =================== DASHBOARD ROUTES ===================
-
-@router.get("/", response_class=HTMLResponse)
-async def trena_dashboard(
- request: Request,
- user_id: str = Depends(require_user_context)
-):
- """Trena main dashboard - Training Management & Skill Assessment"""
-
- context = {
- "request": request,
- "app_name": "Trena - Training Management & Skill Assessment",
- "app_icon": "๐",
- "app_prefix": "/api/v1/trena",
- "tenant_name": getattr(request.state, "tenant_id", "YAZ Healthcare"),
- "user_initials": get_user_initials(user_id),
- "training_summary": await get_training_summary(),
- "quick_stats": await get_quick_training_stats(),
- }
-
- return templates.TemplateResponse("shell.html", context)
-
-
-# =================== API ENDPOINTS ===================
-
-@trena_api_router.post("/training/decisions/create")
-async def create_training_decision(
- criteria: Dict[str, Any] = Body(...),
- alternatives: List[Dict[str, Any]] = Body(...),
- context: Optional[Dict[str, Any]] = Body(None),
- user_id: str = Depends(require_admin_or_manager)
-):
- """
- Create AI-powered training decision using AYRAD-YAZ intelligence
-
- Advanced training decision-making with:
- - Skill gap analysis and prioritization
- - Training program optimization
- - Resource allocation efficiency
- - ROI and effectiveness prediction
- """
- try:
- # Convert input to proper data structures
- training_criteria = TrainingCriteria(
- employee_id=criteria.get("employee_id", ""),
- current_role=criteria.get("current_role", ""),
- department=criteria.get("department", ""),
- skill_assessments=criteria.get("skill_assessments", {}),
- performance_gaps=criteria.get("performance_gaps", []),
- career_goals=criteria.get("career_goals", []),
- time_availability=criteria.get("time_availability", 0),
- learning_preferences=criteria.get("learning_preferences", []),
- regulatory_requirements=criteria.get("regulatory_requirements", []),
- budget_constraints={k: Decimal(str(v)) for k, v in criteria.get("budget_constraints", {}).items()},
- training_history=criteria.get("training_history", {}),
- performance_metrics=criteria.get("performance_metrics", {})
- )
-
- training_alternatives = []
- for alt_data in alternatives:
- alternative = TrainingAlternative(
- program_id=alt_data.get("program_id", f"prog_{len(training_alternatives)}"),
- program_name=alt_data.get("program_name", ""),
- training_type=TrainingType(alt_data.get("training_type", "technical_skills")),
- skill_targets={k: SkillLevel(v) for k, v in alt_data.get("skill_targets", {}).items()},
- duration_hours=alt_data.get("duration_hours", 0),
- delivery_method=alt_data.get("delivery_method", ""),
- cost=Decimal(str(alt_data.get("cost", 0))),
- prerequisites=alt_data.get("prerequisites", []),
- certification_offered=alt_data.get("certification_offered", False),
- effectiveness_score=alt_data.get("effectiveness_score", 0.0),
- engagement_rating=alt_data.get("engagement_rating", 0.0),
- completion_rate=alt_data.get("completion_rate", 0.0),
- roi_estimate=alt_data.get("roi_estimate", 0.0),
- schedule_flexibility=alt_data.get("schedule_flexibility", 0.0)
- )
- training_alternatives.append(alternative)
-
- result = await trena_service.create_training_decision(
- training_criteria, training_alternatives, context or {}
- )
-
- return JSONResponse(content=result)
-
- except ValueError as e:
- raise HTTPException(status_code=400, detail=f"Invalid input data: {str(e)}")
- except TrainingException as e:
- raise HTTPException(status_code=500, detail=str(e))
-
-
-@trena_api_router.post("/skills/assess")
-async def assess_employee_skills(
- employee_id: str = Body(...),
- skill_categories: List[str] = Body(...),
- assessment_criteria: Dict[str, Any] = Body(...),
- context: Optional[Dict[str, Any]] = Body(None),
- user_id: str = Depends(require_admin_or_manager)
-):
- """
- Assess employee skills using comprehensive evaluation methods
-
- Multi-dimensional assessment including:
- - Technical skill proficiency
- - Clinical competency evaluation
- - Leadership capability assessment
- - Performance gap identification
- """
- try:
- result = await trena_service.assess_employee_skills(
- employee_id, skill_categories, assessment_criteria, context or {}
- )
-
- return JSONResponse(content=result)
-
- except TrainingException as e:
- raise HTTPException(status_code=500, detail=str(e))
-
-
-@trena_api_router.post("/programs/optimize")
-async def optimize_training_programs(
- programs: List[Dict[str, Any]] = Body(...),
- organizational_needs: Dict[str, Any] = Body(...),
- resource_constraints: Dict[str, Any] = Body(...),
- context: Optional[Dict[str, Any]] = Body(None),
- user_id: str = Depends(require_admin_or_manager)
-):
- """
- Optimize training program portfolio using AI-driven analysis
-
- Comprehensive optimization including:
- - Program effectiveness analysis
- - Resource utilization optimization
- - Cost-benefit optimization
- - Outcome prediction and planning
- """
- try:
- # Convert programs data to TrainingProgram objects
- training_programs = []
- for prog_data in programs:
- program = TrainingProgram(
- program_id=prog_data.get("program_id", f"prog_{len(training_programs)}"),
- program_name=prog_data.get("program_name", ""),
- training_type=TrainingType(prog_data.get("training_type", "technical_skills")),
- description=prog_data.get("description", ""),
- objectives=prog_data.get("objectives", []),
- target_audience=prog_data.get("target_audience", []),
- duration_hours=prog_data.get("duration_hours", 0),
- delivery_methods=prog_data.get("delivery_methods", []),
- cost_per_participant=Decimal(str(prog_data.get("cost_per_participant", 0))),
- capacity=prog_data.get("capacity", 0),
- instructor_requirements=prog_data.get("instructor_requirements", []),
- materials_required=prog_data.get("materials_required", []),
- assessment_methods=[AssessmentMethod(method) for method in prog_data.get("assessment_methods", [])],
- certification_details=prog_data.get("certification_details", {}),
- effectiveness_metrics=prog_data.get("effectiveness_metrics", {})
- )
- training_programs.append(program)
-
- result = await trena_service.optimize_training_programs(
- training_programs, organizational_needs, resource_constraints, context or {}
- )
-
- return JSONResponse(content=result)
-
- except ValueError as e:
- raise HTTPException(status_code=400, detail=f"Invalid program data: {str(e)}")
- except TrainingException as e:
- raise HTTPException(status_code=500, detail=str(e))
-
-
-@trena_api_router.get("/analytics/dashboard")
-async def get_training_analytics_dashboard(
- timeframe_days: int = Query(default=90, description="Analysis timeframe in days"),
- include_predictions: bool = Query(default=True, description="Include predictive analytics"),
- include_roi: bool = Query(default=True, description="Include ROI analysis"),
- user_id: str = Depends(require_authenticated_user)
-):
- """
- Get comprehensive training analytics dashboard
-
- Provides insights into:
- - Training effectiveness metrics
- - Skill development progress
- - Resource utilization analysis
- - Performance impact assessment
- """
- try:
- timeframe = timedelta(days=timeframe_days)
-
- context = {
- "include_predictions": include_predictions,
- "include_roi": include_roi,
- "user_id": user_id
- }
-
- analytics = await trena_service.get_training_analytics(timeframe, context)
-
- # Add real-time enhancements
- if include_predictions:
- analytics["real_time_metrics"] = await get_real_time_training_metrics()
-
- if include_roi:
- analytics["roi_analysis"] = await get_roi_analysis(timeframe_days)
-
- return JSONResponse(content=analytics)
-
- except Exception as e:
- raise HTTPException(status_code=500, detail=f"Analytics generation failed: {str(e)}")
-
-
-@trena_api_router.get("/employees/{employee_id}/skills")
-async def get_employee_skills(
- employee_id: str,
- include_history: bool = Query(default=False, description="Include skill development history"),
- include_recommendations: bool = Query(default=True, description="Include development recommendations"),
- user_id: str = Depends(require_authenticated_user)
-):
- """
- Get employee skill profile and development information
-
- Provides:
- - Current skill assessments
- - Skill development history
- - Gap analysis and recommendations
- - Certification status
- """
- try:
- skill_profile = await get_employee_skill_profile(
- employee_id, include_history, include_recommendations
- )
-
- return JSONResponse(content=skill_profile)
-
- except Exception as e:
- raise HTTPException(status_code=500, detail=f"Skill profile retrieval failed: {str(e)}")
-
-
-@trena_api_router.get("/programs/catalog")
-async def get_training_program_catalog(
- training_type: Optional[str] = Query(default=None, description="Filter by training type"),
- skill_level: Optional[str] = Query(default=None, description="Filter by skill level"),
- department: Optional[str] = Query(default=None, description="Filter by department"),
- include_metrics: bool = Query(default=True, description="Include effectiveness metrics"),
- user_id: str = Depends(require_authenticated_user)
-):
- """
- Get training program catalog with filtering and metrics
-
- Provides comprehensive program information including:
- - Program descriptions and objectives
- - Prerequisites and requirements
- - Effectiveness metrics and ratings
- - Cost and resource information
- """
- try:
- filters = {}
- if training_type:
- filters["training_type"] = training_type
- if skill_level:
- filters["skill_level"] = skill_level
- if department:
- filters["department"] = department
-
- catalog_data = await get_program_catalog(filters, include_metrics)
-
- return JSONResponse(content=catalog_data)
-
- except Exception as e:
- raise HTTPException(status_code=500, detail=f"Program catalog retrieval failed: {str(e)}")
-
-
-@trena_api_router.post("/assessments/schedule")
-async def schedule_skill_assessment(
- assessment_data: Dict[str, Any] = Body(...),
- user_id: str = Depends(require_admin_or_manager)
-):
- """
- Schedule skill assessment for employee
-
- Supports:
- - Individual skill assessments
- - Competency evaluations
- - Certification assessments
- - Performance reviews
- """
- try:
- # Create assessment object
- assessment = SkillAssessment(
- assessment_id=assessment_data.get("assessment_id", f"assess_{datetime.now().strftime('%Y%m%d_%H%M%S')}"),
- employee_id=assessment_data.get("employee_id", ""),
- skill_category=assessment_data.get("skill_category", ""),
- skill_name=assessment_data.get("skill_name", ""),
- current_level=SkillLevel(assessment_data.get("current_level", "basic")),
- target_level=SkillLevel(assessment_data.get("target_level", "intermediate")),
- assessment_method=AssessmentMethod(assessment_data.get("assessment_method", "written_exam")),
- assessment_date=datetime.fromisoformat(assessment_data.get("assessment_date", datetime.now().isoformat())),
- assessor_id=assessment_data.get("assessor_id", user_id),
- score=assessment_data.get("score", 0.0),
- strengths=assessment_data.get("strengths", []),
- improvement_areas=assessment_data.get("improvement_areas", []),
- recommendations=assessment_data.get("recommendations", []),
- next_assessment_date=datetime.fromisoformat(assessment_data.get("next_assessment_date")) if assessment_data.get("next_assessment_date") else None,
- metadata=assessment_data.get("metadata", {})
- )
-
- # Schedule assessment
- scheduling_result = await schedule_assessment(assessment, user_id)
-
- return JSONResponse(content=scheduling_result)
-
- except ValueError as e:
- raise HTTPException(status_code=400, detail=f"Invalid assessment data: {str(e)}")
- except Exception as e:
- raise HTTPException(status_code=500, detail=f"Assessment scheduling failed: {str(e)}")
-
-
-@trena_api_router.get("/compliance/status")
-async def get_compliance_training_status(
- department: Optional[str] = Query(default=None, description="Filter by department"),
- employee_id: Optional[str] = Query(default=None, description="Filter by employee"),
- training_type: Optional[str] = Query(default=None, description="Filter by training type"),
- user_id: str = Depends(require_authenticated_user)
-):
- """
- Get compliance training status and requirements
-
- Provides:
- - Current compliance status
- - Upcoming requirements
- - Overdue training alerts
- - Certification expiration tracking
- """
- try:
- filters = {}
- if department:
- filters["department"] = department
- if employee_id:
- filters["employee_id"] = employee_id
- if training_type:
- filters["training_type"] = training_type
-
- compliance_data = await get_compliance_status(filters)
-
- return JSONResponse(content=compliance_data)
-
- except Exception as e:
- raise HTTPException(status_code=500, detail=f"Compliance status retrieval failed: {str(e)}")
-
-
-@trena_api_router.get("/performance/impact")
-async def get_training_performance_impact(
- training_program_id: Optional[str] = Query(default=None, description="Filter by program"),
- timeframe_months: int = Query(default=6, description="Analysis timeframe in months"),
- user_id: str = Depends(require_authenticated_user)
-):
- """
- Get training performance impact analysis
-
- Analyzes:
- - Performance improvement metrics
- - Skills application in workplace
- - Productivity impact
- - Quality metrics correlation
- """
- try:
- impact_analysis = await analyze_training_performance_impact(
- training_program_id, timeframe_months
- )
-
- return JSONResponse(content=impact_analysis)
-
- except Exception as e:
- raise HTTPException(status_code=500, detail=f"Performance impact analysis failed: {str(e)}")
-
-
-# =================== HELPER FUNCTIONS ===================
-
-def get_user_initials(user_id: str) -> str:
- """Get user initials for display"""
- return user_id[0].upper() if user_id else "TR"
-
-
-async def get_training_summary() -> Dict[str, Any]:
- """Get training summary for dashboard"""
- return {
- "total_employees": 542,
- "active_training_programs": 28,
- "completed_assessments": 187,
- "compliance_rate": 0.94,
- "average_skill_improvement": 0.23,
- "training_satisfaction": 0.87
- }
-
-
-async def get_quick_training_stats() -> Dict[str, Any]:
- """Get quick training statistics"""
- return {
- "program_completion_rate": 0.88,
- "certification_success_rate": 0.85,
- "training_roi": 3.2,
- "skill_gap_closure_rate": 0.76,
- "employee_engagement": 0.82,
- "time_to_competency": 4.2 # months
- }
-
-
-async def get_real_time_training_metrics() -> Dict[str, Any]:
- """Get real-time training metrics"""
- return {
- "active_training_sessions": 12,
- "assessments_in_progress": 8,
- "certifications_expiring_this_month": 15,
- "overdue_compliance_training": 6,
- "skill_assessments_scheduled": 23,
- "last_updated": datetime.now().isoformat()
- }
-
-
-async def get_roi_analysis(timeframe_days: int) -> Dict[str, Any]:
- """Get training ROI analysis"""
- return {
- "total_training_investment": 485000,
- "productivity_gains": 1550000,
- "quality_improvements": 325000,
- "retention_savings": 275000,
- "total_benefits": 2150000,
- "net_roi": 3.43,
- "payback_period_months": 8.2,
- "cost_per_employee": 895
- }
-
-
-async def get_employee_skill_profile(
- employee_id: str,
- include_history: bool,
- include_recommendations: bool
-) -> Dict[str, Any]:
- """Get employee skill profile"""
- profile = {
- "employee_id": employee_id,
- "current_role": "Clinical Specialist",
- "department": "Critical Care",
- "skill_assessments": {
- "clinical_skills": {
- "patient_assessment": {"level": "advanced", "score": 0.85},
- "medication_administration": {"level": "expert", "score": 0.92},
- "emergency_response": {"level": "intermediate", "score": 0.74}
- },
- "technical_skills": {
- "equipment_operation": {"level": "advanced", "score": 0.88},
- "laboratory_procedures": {"level": "intermediate", "score": 0.71},
- "information_systems": {"level": "basic", "score": 0.62}
- },
- "leadership_skills": {
- "team_management": {"level": "intermediate", "score": 0.69},
- "communication": {"level": "advanced", "score": 0.84},
- "decision_making": {"level": "intermediate", "score": 0.73}
- }
- },
- "overall_competency_score": 0.78,
- "certifications": [
- {"name": "BLS", "status": "current", "expires": "2025-06-15"},
- {"name": "ACLS", "status": "current", "expires": "2025-08-20"},
- {"name": "Critical Care Certification", "status": "pending_renewal", "expires": "2025-01-10"}
- ]
- }
-
- if include_history:
- profile["skill_development_history"] = [
- {"date": "2024-09-15", "skill": "patient_assessment", "previous_level": "intermediate", "new_level": "advanced"},
- {"date": "2024-08-22", "skill": "emergency_response", "previous_level": "basic", "new_level": "intermediate"},
- {"date": "2024-07-10", "skill": "medication_administration", "previous_level": "advanced", "new_level": "expert"}
- ]
-
- if include_recommendations:
- profile["development_recommendations"] = [
- {
- "priority": "high",
- "skill": "information_systems",
- "current_level": "basic",
- "target_level": "intermediate",
- "recommended_training": "Healthcare IT Fundamentals",
- "timeline": "3 months"
- },
- {
- "priority": "medium",
- "skill": "team_management",
- "current_level": "intermediate",
- "target_level": "advanced",
- "recommended_training": "Leadership in Healthcare",
- "timeline": "6 months"
- }
- ]
-
- return profile
-
-
-async def get_program_catalog(filters: Dict[str, Any], include_metrics: bool) -> Dict[str, Any]:
- """Get training program catalog"""
- programs = [
- {
- "program_id": "PROG_001",
- "program_name": "Advanced Clinical Skills",
- "training_type": "clinical_competency",
- "description": "Comprehensive clinical skills development program",
- "duration_hours": 40,
- "delivery_methods": ["classroom", "simulation", "clinical_practice"],
- "prerequisites": ["Basic Clinical Training"],
- "certification_offered": True,
- "target_roles": ["Staff Nurse", "Clinical Specialist"],
- "skill_targets": {
- "patient_assessment": "advanced",
- "clinical_judgment": "advanced",
- "procedure_execution": "expert"
- }
- },
- {
- "program_id": "PROG_002",
- "program_name": "Leadership Development Program",
- "training_type": "leadership_development",
- "description": "Develop leadership capabilities for healthcare professionals",
- "duration_hours": 60,
- "delivery_methods": ["workshop", "mentoring", "project_based"],
- "prerequisites": ["2+ years experience"],
- "certification_offered": True,
- "target_roles": ["Charge Nurse", "Department Manager"],
- "skill_targets": {
- "team_management": "advanced",
- "strategic_thinking": "intermediate",
- "change_management": "advanced"
- }
- }
- ]
-
- # Apply filters
- filtered_programs = programs
- if filters.get("training_type"):
- filtered_programs = [p for p in filtered_programs if p["training_type"] == filters["training_type"]]
-
- result = {
- "programs": filtered_programs,
- "total_count": len(filtered_programs),
- "filters_applied": filters
- }
-
- if include_metrics:
- result["catalog_metrics"] = {
- "programs_by_type": {"clinical_competency": 1, "leadership_development": 1},
- "average_duration": 50,
- "certification_programs": 2,
- "most_popular": "Advanced Clinical Skills"
- }
-
- return result
-
-
-async def schedule_assessment(assessment: SkillAssessment, user_id: str) -> Dict[str, Any]:
- """Schedule skill assessment"""
- return {
- "status": "scheduled",
- "assessment_id": assessment.assessment_id,
- "employee_id": assessment.employee_id,
- "skill_category": assessment.skill_category,
- "skill_name": assessment.skill_name,
- "assessment_method": assessment.assessment_method.value,
- "scheduled_date": assessment.assessment_date.isoformat(),
- "assessor_id": assessment.assessor_id,
- "next_assessment": assessment.next_assessment_date.isoformat() if assessment.next_assessment_date else None,
- "scheduled_by": user_id,
- "scheduled_at": datetime.now().isoformat(),
- "confirmation_number": f"ASSESS_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
- }
-
-
-async def get_compliance_status(filters: Dict[str, Any]) -> Dict[str, Any]:
- """Get compliance training status"""
- return {
- "overall_compliance_rate": 0.94,
- "compliance_by_department": {
- "Critical Care": 0.96,
- "Emergency": 0.92,
- "Surgery": 0.95,
- "Medical": 0.93
- },
- "upcoming_requirements": [
- {"employee_id": "EMP_001", "training": "BLS Renewal", "due_date": "2024-12-15"},
- {"employee_id": "EMP_002", "training": "HIPAA Training", "due_date": "2024-12-20"},
- {"employee_id": "EMP_003", "training": "Fire Safety", "due_date": "2024-12-25"}
- ],
- "overdue_training": [
- {"employee_id": "EMP_015", "training": "Infection Control", "overdue_days": 5},
- {"employee_id": "EMP_028", "training": "Code Blue Training", "overdue_days": 12}
- ],
- "certification_expirations": [
- {"employee_id": "EMP_042", "certification": "Critical Care Cert", "expires": "2025-01-10"},
- {"employee_id": "EMP_055", "certification": "ACLS", "expires": "2025-01-15"}
- ],
- "compliance_trends": {
- "this_month": 0.94,
- "last_month": 0.92,
- "trend": "improving"
- }
- }
-
-
-async def analyze_training_performance_impact(
- program_id: Optional[str],
- timeframe_months: int
-) -> Dict[str, Any]:
- """Analyze training performance impact"""
- return {
- "program_id": program_id or "all_programs",
- "analysis_period_months": timeframe_months,
- "performance_improvements": {
- "patient_satisfaction": 0.12,
- "quality_metrics": 0.18,
- "efficiency_gains": 0.15,
- "error_reduction": 0.22,
- "productivity_increase": 0.14
- },
- "skill_application_rates": {
- "immediate_application": 0.85,
- "3_month_retention": 0.78,
- "6_month_retention": 0.72,
- "workplace_integration": 0.69
- },
- "organizational_impact": {
- "employee_engagement": 0.16,
- "retention_improvement": 0.08,
- "promotion_readiness": 0.25,
- "leadership_pipeline": 0.18
- },
- "financial_impact": {
- "cost_savings": 285000,
- "revenue_impact": 450000,
- "efficiency_gains": 125000,
- "total_benefit": 860000
- },
- "benchmarking": {
- "industry_average_improvement": 0.12,
- "our_performance": 0.16,
- "relative_performance": "above_average"
- }
- }
\ No newline at end of file
diff --git a/src/apps/trena/api/schemas.py b/src/apps/trena/api/schemas.py
deleted file mode 100644
index c2cf059c3100215f017ee603e923f8f751e6627e..0000000000000000000000000000000000000000
--- a/src/apps/trena/api/schemas.py
+++ /dev/null
@@ -1,221 +0,0 @@
-"""
-Trena API Schemas - Training Coordination & Continuing Education
-Comprehensive OpenAPI 3.1 documentation for healthcare training management
-
-Clinical Context: Coordinate continuing medical education (CME), mandatory
-training, certification tracking, and competency assessments for healthcare staff.
-Critical for regulatory compliance and quality improvement.
-
-Standards Compliance:
-- ACCME (Accreditation Council for Continuing Medical Education)
-- Joint Commission training requirements
-- OSHA healthcare worker training mandates
-- State licensing board CME requirements
-
-Performance Targets:
-- Enrollment: <100ms
-- Course completion: <150ms
-- Certificate generation: <300ms
-- Compliance reporting: <500ms
-
-Security: RBAC (roles: training_coordinator, instructor, learner)
-Multi-Tenancy: Facility-level with organization-wide catalog sharing
-Caching: Course catalog (4h), learner progress (15min), certificates (permanent)
-Audit: All training activities logged (compliance + accreditation)
-"""
-
-from datetime import datetime, date
-from decimal import Decimal
-from enum import Enum
-from typing import Optional, List, Dict, Any
-from uuid import UUID
-
-from pydantic import BaseModel, Field, ConfigDict
-
-
-# ============================================================================
-# ENUMS
-# ============================================================================
-
-class CourseCategory(str, Enum):
- """Training course categories."""
- CME = "cme" # Continuing Medical Education
- MANDATORY_COMPLIANCE = "mandatory_compliance" # OSHA, HIPAA, etc.
- CLINICAL_COMPETENCY = "clinical_competency" # Skills validation
- SAFETY_TRAINING = "safety_training" # Fire, hazmat, etc.
- TECHNOLOGY = "technology" # EMR, equipment training
- LEADERSHIP = "leadership" # Management development
-
-
-class CompletionStatus(str, Enum):
- """Course completion status."""
- NOT_STARTED = "not_started"
- IN_PROGRESS = "in_progress"
- COMPLETED = "completed"
- FAILED = "failed"
- EXPIRED = "expired" # Requires renewal
-
-
-# ============================================================================
-# REQUEST SCHEMAS
-# ============================================================================
-
-class CreateCourseRequest(BaseModel):
- """Create training course.
-
- Performance: <150ms
- Security: training_coordinator role required
- """
-
- course_code: str = Field(..., pattern=r"^[A-Z0-9-]+$", max_length=50)
- course_name: str = Field(..., min_length=5, max_length=200)
- category: CourseCategory
-
- description: str = Field(..., min_length=20, max_length=2000)
- learning_objectives: List[str] = Field(..., min_length=1)
-
- duration_minutes: int = Field(..., ge=15, le=480)
- cme_credits: Optional[Decimal] = Field(None, ge=0, le=100)
-
- is_mandatory: bool = Field(False)
- renewal_period_days: Optional[int] = Field(None, ge=1)
-
- passing_score: int = Field(70, ge=0, le=100)
-
- model_config = ConfigDict(json_schema_extra={"examples": [{
- "course_code": "HIPAA-2025",
- "course_name": "HIPAA Privacy and Security Annual Training",
- "category": "mandatory_compliance",
- "description": "Annual HIPAA training covering privacy, security, breach notification...",
- "learning_objectives": ["Identify PHI", "Understand minimum necessary"],
- "duration_minutes": 45,
- "cme_credits": None,
- "is_mandatory": True,
- "renewal_period_days": 365,
- "passing_score": 80
- }]})
-
-
-class EnrollLearnerRequest(BaseModel):
- """Enroll user in training course.
-
- Performance: <100ms
- Security: training_coordinator or self-enrollment
- """
-
- course_id: UUID
- learner_id: UUID
- enrollment_date: date = Field(..., examples=["2025-07-20"])
-
- due_date: Optional[date] = Field(None,
- description="Completion deadline for mandatory training"
- )
-
- assigned_by_id: Optional[UUID] = Field(None,
- description="Who assigned the training (if mandatory)"
- )
-
- model_config = ConfigDict(json_schema_extra={"examples": [{
- "course_id": "770e8400-e29b-41d4-a716-446655440000",
- "learner_id": "880e8400-e29b-41d4-a716-446655440000",
- "enrollment_date": "2025-07-20",
- "due_date": "2025-08-20",
- "assigned_by_id": "660e8400-e29b-41d4-a716-446655440000"
- }]})
-
-
-class RecordCompletionRequest(BaseModel):
- """Record course completion.
-
- Performance: <150ms (includes certificate generation)
- Security: learner (self) or training_coordinator
- """
-
- enrollment_id: UUID
- completion_date: datetime = Field(..., examples=["2025-07-25T14:30:00Z"])
-
- score: int = Field(..., ge=0, le=100)
- time_spent_minutes: int = Field(..., ge=1)
-
- passed: bool
-
- model_config = ConfigDict(json_schema_extra={"examples": [{
- "enrollment_id": "880e8400-e29b-41d4-a716-446655440000",
- "completion_date": "2025-07-25T14:30:00Z",
- "score": 95,
- "time_spent_minutes": 50,
- "passed": True
- }]})
-
-
-# ============================================================================
-# RESPONSE SCHEMAS
-# ============================================================================
-
-class CourseResponse(BaseModel):
- """Course details."""
-
- id: UUID
- course_code: str
- course_name: str
- category: CourseCategory
- description: str
-
- duration_minutes: int
- cme_credits: Optional[Decimal]
-
- is_mandatory: bool
- enrollment_count: int
- completion_rate: Decimal
-
- created_at: datetime
-
- model_config = ConfigDict(json_schema_extra={"examples": [{
- "id": "770e8400-e29b-41d4-a716-446655440000",
- "course_code": "HIPAA-2025",
- "course_name": "HIPAA Privacy and Security Annual Training",
- "category": "mandatory_compliance",
- "description": "Annual HIPAA training...",
- "duration_minutes": 45,
- "cme_credits": None,
- "is_mandatory": True,
- "enrollment_count": 250,
- "completion_rate": "87.5",
- "created_at": "2025-01-01T00:00:00Z"
- }]})
-
-
-class TrainingComplianceResponse(BaseModel):
- """Training compliance dashboard.
-
- Clinical Context: Monitor staff training compliance for regulatory
- readiness and accreditation.
- """
-
- total_staff: int
- compliant_count: int
- non_compliant_count: int
- compliance_rate: Decimal
-
- overdue_training_count: int
- expiring_soon_count: int = Field(description="Expiring within 30 days")
-
- by_category: Dict[str, Dict[str, int]] = Field(
- examples=[{
- "mandatory_compliance": {"compliant": 240, "non_compliant": 10},
- "cme": {"compliant": 200, "non_compliant": 50}
- }]
- )
-
- model_config = ConfigDict(json_schema_extra={"examples": [{
- "total_staff": 250,
- "compliant_count": 225,
- "non_compliant_count": 25,
- "compliance_rate": "90.0",
- "overdue_training_count": 15,
- "expiring_soon_count": 35,
- "by_category": {
- "mandatory_compliance": {"compliant": 240, "non_compliant": 10},
- "cme": {"compliant": 200, "non_compliant": 50}
- }
- }]})
diff --git a/src/apps/trena/models.py b/src/apps/trena/models.py
deleted file mode 100644
index 00d5446ccc4e8619f1eb5b3f6d412e41f2a69095..0000000000000000000000000000000000000000
--- a/src/apps/trena/models.py
+++ /dev/null
@@ -1,424 +0,0 @@
-"""
-Trena (Training Coordination) Domain Models
-
-Clinical Context: Staff training, continuing education, certification tracking,
-competency assessment, mandatory training compliance.
-
-Standards Compliance:
-- Joint Commission training requirements
-- OSHA mandatory training
-- HIPAA training compliance
-- State licensure requirements
-- Professional certification standards
-
-Performance: <100ms for training queries, <200ms for compliance reports
-"""
-
-from __future__ import annotations
-
-from datetime import datetime, date
-from typing import Optional, List
-from enum import Enum
-from uuid import UUID, uuid4
-from decimal import Decimal
-
-from sqlmodel import SQLModel, Field, Relationship, Column, JSON
-from pydantic import validator
-
-from core.database.mixins import TenantMixin, TimestampMixin, SoftDeleteMixin
-
-
-# ============================================================================
-# Enumerations
-# ============================================================================
-
-
-class TrainingType(str, Enum):
- """Type of training"""
- ORIENTATION = "orientation"
- MANDATORY = "mandatory"
- CONTINUING_EDUCATION = "continuing_education"
- COMPETENCY = "competency"
- CERTIFICATION = "certification"
- SKILL_VALIDATION = "skill_validation"
- SAFETY = "safety"
- COMPLIANCE = "compliance"
-
-
-class TrainingStatus(str, Enum):
- """Training status"""
- NOT_STARTED = "not_started"
- IN_PROGRESS = "in_progress"
- COMPLETED = "completed"
- EXPIRED = "expired"
- FAILED = "failed"
- WAIVED = "waived"
-
-
-class CourseStatus(str, Enum):
- """Course availability status"""
- DRAFT = "draft"
- ACTIVE = "active"
- ARCHIVED = "archived"
- RETIRED = "retired"
-
-
-class DeliveryMethod(str, Enum):
- """Training delivery method"""
- IN_PERSON = "in_person"
- ONLINE = "online"
- HYBRID = "hybrid"
- SELF_PACED = "self_paced"
- HANDS_ON = "hands_on"
- SIMULATION = "simulation"
-
-
-class CompetencyLevel(str, Enum):
- """Competency assessment level"""
- NOVICE = "novice"
- ADVANCED_BEGINNER = "advanced_beginner"
- COMPETENT = "competent"
- PROFICIENT = "proficient"
- EXPERT = "expert"
-
-
-class CertificationStatus(str, Enum):
- """Professional certification status"""
- ACTIVE = "active"
- EXPIRED = "expired"
- SUSPENDED = "suspended"
- REVOKED = "revoked"
- PENDING_RENEWAL = "pending_renewal"
-
-
-# ============================================================================
-# Domain Models
-# ============================================================================
-
-
-class TrainingCourse(TenantMixin, TimestampMixin, SoftDeleteMixin, SQLModel, table=True):
- """
- Training Course
-
- Clinical Context: Training courses and educational programs
- Standards: Joint Commission, OSHA
- Performance: <50ms for course lookup
- """
- __tablename__ = "training_courses"
- __table_args__ = {"schema": "trena"}
-
- id: UUID = Field(default_factory=uuid4, primary_key=True)
- tenant_id: UUID = Field(foreign_key="core.tenants.id", index=True)
-
- # Course identification
- course_code: str = Field(max_length=50, index=True, unique=True)
- title: str = Field(max_length=200)
- description: Optional[str] = Field(default=None, max_length=2000)
-
- # Classification
- training_type: TrainingType = Field(index=True)
- category: str = Field(max_length=100, index=True)
-
- # Delivery
- delivery_method: DeliveryMethod = Field(index=True)
- duration_hours: Optional[Decimal] = Field(default=None, max_digits=5, decimal_places=2)
-
- # Requirements
- is_mandatory: bool = Field(default=False, index=True)
- is_annual: bool = Field(default=False)
- is_initial: bool = Field(default=False)
-
- # Prerequisites
- prerequisites: Optional[List[str]] = Field(default=None, sa_column=Column(JSON))
-
- # Credits
- ceu_credits: Optional[Decimal] = Field(default=None, max_digits=4, decimal_places=2)
- cme_credits: Optional[Decimal] = Field(default=None, max_digits=4, decimal_places=2)
-
- # Content
- learning_objectives: Optional[List[str]] = Field(default=None, sa_column=Column(JSON))
- topics: Optional[List[str]] = Field(default=None, sa_column=Column(JSON))
-
- # Assessment
- requires_exam: bool = Field(default=False)
- passing_score: Optional[Decimal] = Field(default=None, max_digits=5, decimal_places=2)
- max_attempts: Optional[int] = Field(default=None)
-
- # Validity
- validity_months: Optional[int] = Field(default=None) # How long cert is valid
-
- # Status
- status: CourseStatus = Field(default=CourseStatus.DRAFT, index=True)
- is_active: bool = Field(default=True, index=True)
-
- # Instructor
- instructor_id: Optional[UUID] = Field(default=None, foreign_key="core.users.id")
-
- # Metadata
- metadata: Optional[dict] = Field(default=None, sa_column=Column(JSON))
-
- # Relationships
- enrollments: List["TrainingEnrollment"] = Relationship(back_populates="course")
- sessions: List["TrainingSession"] = Relationship(back_populates="course")
-
-
-class TrainingSession(TenantMixin, TimestampMixin, SoftDeleteMixin, SQLModel, table=True):
- """
- Training Session - Scheduled course offering
-
- Clinical Context: Specific date/time offering of a course
- Performance: <50ms for session lookup
- """
- __tablename__ = "training_sessions"
- __table_args__ = {"schema": "trena"}
-
- id: UUID = Field(default_factory=uuid4, primary_key=True)
- tenant_id: UUID = Field(foreign_key="core.tenants.id", index=True)
-
- course_id: UUID = Field(foreign_key="trena.training_courses.id", index=True)
-
- # Session details
- session_number: str = Field(max_length=50, index=True)
-
- # Scheduling
- start_date: date = Field(index=True)
- start_time: Optional[str] = Field(default=None, max_length=10) # HH:MM format
- end_date: Optional[date] = Field(default=None)
- end_time: Optional[str] = Field(default=None, max_length=10)
-
- # Location
- location: Optional[str] = Field(default=None, max_length=200)
- room: Optional[str] = Field(default=None, max_length=100)
- online_meeting_link: Optional[str] = Field(default=None, max_length=500)
-
- # Capacity
- max_participants: Optional[int] = Field(default=None)
- enrolled_count: int = Field(default=0)
- waitlist_count: int = Field(default=0)
-
- # Instructor
- instructor_id: Optional[UUID] = Field(default=None, foreign_key="core.users.id")
-
- # Status
- is_cancelled: bool = Field(default=False, index=True)
- cancellation_reason: Optional[str] = Field(default=None, max_length=500)
-
- # Notes
- notes: Optional[str] = Field(default=None, max_length=1000)
-
- # Relationships
- course: "TrainingCourse" = Relationship(back_populates="sessions")
- enrollments: List["TrainingEnrollment"] = Relationship(back_populates="session")
-
-
-class TrainingEnrollment(TenantMixin, TimestampMixin, SQLModel, table=True):
- """
- Training Enrollment - Employee enrollment in course
-
- Clinical Context: Track employee training participation
- Performance: <100ms for enrollment creation
- """
- __tablename__ = "training_enrollments"
- __table_args__ = {"schema": "trena"}
-
- id: UUID = Field(default_factory=uuid4, primary_key=True)
- tenant_id: UUID = Field(foreign_key="core.tenants.id", index=True)
-
- course_id: UUID = Field(foreign_key="trena.training_courses.id", index=True)
- session_id: Optional[UUID] = Field(default=None, foreign_key="trena.training_sessions.id", index=True)
- employee_id: UUID = Field(foreign_key="core.users.id", index=True)
-
- # Enrollment details
- enrollment_date: date = Field(default_factory=date.today, index=True)
- is_waitlisted: bool = Field(default=False)
-
- # Progress
- status: TrainingStatus = Field(default=TrainingStatus.NOT_STARTED, index=True)
- progress_percentage: Decimal = Field(default=0, max_digits=5, decimal_places=2)
-
- # Completion
- completion_date: Optional[date] = Field(default=None, index=True)
- expiration_date: Optional[date] = Field(default=None, index=True)
-
- # Assessment
- exam_score: Optional[Decimal] = Field(default=None, max_digits=5, decimal_places=2)
- exam_attempts: int = Field(default=0)
- passed: Optional[bool] = Field(default=None)
-
- # Credits awarded
- ceu_credits_earned: Optional[Decimal] = Field(default=None, max_digits=4, decimal_places=2)
- cme_credits_earned: Optional[Decimal] = Field(default=None, max_digits=4, decimal_places=2)
-
- # Instructor feedback
- instructor_notes: Optional[str] = Field(default=None, max_length=2000)
-
- # Certificate
- certificate_number: Optional[str] = Field(default=None, max_length=100)
- certificate_issued_date: Optional[date] = Field(default=None)
-
- # Notes
- notes: Optional[str] = Field(default=None, max_length=1000)
-
- # Relationships
- course: "TrainingCourse" = Relationship(back_populates="enrollments")
- session: Optional["TrainingSession"] = Relationship(back_populates="enrollments")
-
-
-class Competency(TenantMixin, TimestampMixin, SoftDeleteMixin, SQLModel, table=True):
- """
- Competency Definition
-
- Clinical Context: Required clinical or administrative competencies
- Standards: Joint Commission competency requirements
- Performance: <50ms for competency lookup
- """
- __tablename__ = "competencies"
- __table_args__ = {"schema": "trena"}
-
- id: UUID = Field(default_factory=uuid4, primary_key=True)
- tenant_id: UUID = Field(foreign_key="core.tenants.id", index=True)
-
- # Competency identification
- competency_code: str = Field(max_length=50, index=True, unique=True)
- name: str = Field(max_length=200)
- description: Optional[str] = Field(default=None, max_length=2000)
-
- # Classification
- category: str = Field(max_length=100, index=True)
- subcategory: Optional[str] = Field(default=None, max_length=100)
-
- # Job roles
- applicable_roles: Optional[List[str]] = Field(default=None, sa_column=Column(JSON))
-
- # Requirements
- is_mandatory: bool = Field(default=False)
- is_annual: bool = Field(default=False)
-
- # Assessment criteria
- assessment_method: Optional[str] = Field(default=None, max_length=500)
- performance_criteria: Optional[List[str]] = Field(default=None, sa_column=Column(JSON))
-
- # Validity
- validity_months: Optional[int] = Field(default=None)
-
- # Status
- is_active: bool = Field(default=True, index=True)
-
- # Relationships
- assessments: List["CompetencyAssessment"] = Relationship(back_populates="competency")
-
-
-class CompetencyAssessment(TenantMixin, TimestampMixin, SQLModel, table=True):
- """
- Competency Assessment - Employee competency evaluation
-
- Clinical Context: Track competency validation for staff
- Performance: <100ms for assessment recording
- """
- __tablename__ = "competency_assessments"
- __table_args__ = {"schema": "trena"}
-
- id: UUID = Field(default_factory=uuid4, primary_key=True)
- tenant_id: UUID = Field(foreign_key="core.tenants.id", index=True)
-
- competency_id: UUID = Field(foreign_key="trena.competencies.id", index=True)
- employee_id: UUID = Field(foreign_key="core.users.id", index=True)
-
- # Assessment details
- assessment_date: date = Field(default_factory=date.today, index=True)
- assessor_id: UUID = Field(foreign_key="core.users.id")
-
- # Results
- competency_level: CompetencyLevel = Field(index=True)
- is_competent: bool = Field(default=False, index=True)
- score: Optional[Decimal] = Field(default=None, max_digits=5, decimal_places=2)
-
- # Validity
- valid_until: Optional[date] = Field(default=None, index=True)
-
- # Observations
- strengths: Optional[str] = Field(default=None, max_length=2000)
- areas_for_improvement: Optional[str] = Field(default=None, max_length=2000)
- action_plan: Optional[str] = Field(default=None, max_length=2000)
-
- # Follow-up
- requires_followup: bool = Field(default=False)
- followup_date: Optional[date] = Field(default=None)
- followup_completed: bool = Field(default=False)
-
- # Attachments
- attachments: Optional[List[str]] = Field(default=None, sa_column=Column(JSON))
-
- # Relationships
- competency: "Competency" = Relationship(back_populates="assessments")
-
-
-class Certification(TenantMixin, TimestampMixin, SoftDeleteMixin, SQLModel, table=True):
- """
- Professional Certification
-
- Clinical Context: Track professional licenses and certifications
- Standards: State licensure, professional boards
- Performance: <100ms for certification lookup
- """
- __tablename__ = "certifications"
- __table_args__ = {"schema": "trena"}
-
- id: UUID = Field(default_factory=uuid4, primary_key=True)
- tenant_id: UUID = Field(foreign_key="core.tenants.id", index=True)
-
- employee_id: UUID = Field(foreign_key="core.users.id", index=True)
-
- # Certification details
- certification_type: str = Field(max_length=100, index=True) # RN, MD, BLS, ACLS
- certification_name: str = Field(max_length=200)
- certifying_body: str = Field(max_length=200)
-
- # Identification
- certification_number: str = Field(max_length=100, index=True)
-
- # Dates
- issue_date: date = Field(index=True)
- expiration_date: date = Field(index=True)
- last_verification_date: Optional[date] = Field(default=None)
-
- # Status
- status: CertificationStatus = Field(default=CertificationStatus.ACTIVE, index=True)
-
- # Renewal
- renewal_required: bool = Field(default=True)
- renewal_notification_sent: bool = Field(default=False)
- renewal_credits_required: Optional[int] = Field(default=None)
- renewal_credits_earned: Optional[int] = Field(default=None)
-
- # Verification
- verified: bool = Field(default=False)
- verification_method: Optional[str] = Field(default=None, max_length=200)
- verification_date: Optional[date] = Field(default=None)
- verified_by: Optional[UUID] = Field(default=None, foreign_key="core.users.id")
-
- # Attachments (scanned certificates)
- attachment_url: Optional[str] = Field(default=None, max_length=500)
-
- # Notes
- notes: Optional[str] = Field(default=None, max_length=1000)
-
-
-# ============================================================================
-# Export all models
-# ============================================================================
-
-__all__ = [
- "TrainingType",
- "TrainingStatus",
- "CourseStatus",
- "DeliveryMethod",
- "CompetencyLevel",
- "CertificationStatus",
- "TrainingCourse",
- "TrainingSession",
- "TrainingEnrollment",
- "Competency",
- "CompetencyAssessment",
- "Certification",
-]
diff --git a/src/apps/trena/repository.py b/src/apps/trena/repository.py
deleted file mode 100644
index e1e1c34c6db53a55bcd0156a6db952b5edd5deee..0000000000000000000000000000000000000000
--- a/src/apps/trena/repository.py
+++ /dev/null
@@ -1,36 +0,0 @@
-"""
-Trena Repository - Database Access Layer for Training Management
-Lightweight repository for courses, certifications, training sessions, and learner data
-"""
-
-from typing import List, Optional, Dict, Any
-from datetime import datetime
-from uuid import UUID
-from sqlalchemy.orm import Session
-
-from core.optimization.optimized_repository import OptimizedRepository
-
-import logging
-
-logger = logging.getLogger(__name__)
-
-
-class TrenaRepository(OptimizedRepository):
- """Repository for training management data"""
-
- def __init__(self, session: Session):
- super().__init__(session)
-
- # Course operations would go here - models to be created
- # Certification tracking would go here - models to be created
- # Training session management would go here - models to be created
- # Learner progress tracking would go here - models to be created
-
- async def placeholder_operation(self):
- """Placeholder for future implementation"""
- pass
-
-
-def get_trena_repository(session: Session) -> TrenaRepository:
- """Get Trena repository instance"""
- return TrenaRepository(session)
diff --git a/src/apps/trena/router.py b/src/apps/trena/router.py
deleted file mode 100644
index e11d3e3b5b903d34f5d6244813b2ad45bc7ca279..0000000000000000000000000000000000000000
--- a/src/apps/trena/router.py
+++ /dev/null
@@ -1,44 +0,0 @@
-"""
-Trena router - Training Management
-"""
-from fastapi import APIRouter, Request
-from fastapi.templating import Jinja2Templates
-from pathlib import Path
-from ui.navigation import get_nav_modules, get_quick_actions
-
-router = APIRouter()
-
-# Initialize templates
-templates_dir = Path(__file__).parent.parent.parent / "ui/templates"
-templates = Jinja2Templates(directory=str(templates_dir))
-
-@router.get("/")
-@router.get("")
-async def trena_dashboard(request: Request):
- """
- Trena Dashboard - Training Coordination
-
- Performance: <200ms p95
- Features: Training schedules, certification tracking, competency management
- """
- context = {
- "request": request,
- "app_title": "Trena",
- "app_description": "Training Coordination & Management",
- "quick_metrics": [
- {"value": "28", "label": "Active Programs", "color": "blue", "icon": ''},
- {"value": "156", "label": "Trainees", "color": "green", "icon": ''},
- {"value": "92%", "label": "Completion Rate", "color": "purple", "icon": ''},
- {"value": "12", "label": "Sessions Today", "color": "orange", "icon": ''},
- ],
- "primary_actions": [{"label": "New Session", "url": "/trena/sessions/new", "color": "blue", "icon": ''}],
- "quick_links": [
- {"label": "Training Programs", "url": "/trena/programs", "icon": ''},
- {"label": "Certifications", "url": "/trena/certifications", "icon": ''},
- ],
- "recent_items": [{"title": "Training schedule updated", "time": "10 min ago"}],
- "nav_modules": get_nav_modules(),
- "content_title": "Training Coordination",
- "main_content": "Comprehensive training program management and certification tracking.
"
- }
- return templates.TemplateResponse("shared/unified_app.html", context)
diff --git a/src/apps/trena/schemas.py b/src/apps/trena/schemas.py
deleted file mode 100644
index f791cf391d9fd6dd041782572e67491edf887f69..0000000000000000000000000000000000000000
--- a/src/apps/trena/schemas.py
+++ /dev/null
@@ -1,487 +0,0 @@
-"""
-Trena (Training Coordination) API Schemas
-
-Pydantic request/response schemas for all API endpoints.
-
-Clinical Context: Staff training, continuing education, certification tracking
-Standards: Joint Commission, OSHA, HIPAA training compliance
-Performance: <100ms for reads, <200ms for writes
-"""
-
-from __future__ import annotations
-
-from datetime import date, datetime
-from typing import Optional, List
-from decimal import Decimal
-from uuid import UUID
-
-from pydantic import BaseModel, Field, ConfigDict, field_validator
-
-from .models import (
- TrainingType,
- TrainingStatus,
- CourseStatus,
- DeliveryMethod,
- CompetencyLevel,
- CertificationStatus,
-)
-
-
-# ============================================================================
-# Training Course Schemas
-# ============================================================================
-
-
-class TrainingCourseBase(BaseModel):
- """Base training course fields"""
- course_code: str = Field(..., min_length=1, max_length=50, description="Unique course code")
- title: str = Field(..., min_length=1, max_length=200, description="Course title")
- description: Optional[str] = Field(None, max_length=2000, description="Course description")
-
- training_type: TrainingType = Field(..., description="Type of training")
- category: str = Field(..., max_length=100, description="Course category")
-
- delivery_method: DeliveryMethod = Field(..., description="How course is delivered")
- duration_hours: Optional[Decimal] = Field(None, description="Course duration in hours")
-
- is_mandatory: bool = Field(False, description="Whether training is mandatory")
- is_annual: bool = Field(False, description="Whether training repeats annually")
-
- ceu_credits: Optional[Decimal] = Field(None, description="Continuing education credits")
- cme_credits: Optional[Decimal] = Field(None, description="Continuing medical education credits")
-
- requires_exam: bool = Field(False, description="Whether course has exam")
- passing_score: Optional[Decimal] = Field(None, description="Passing score percentage")
-
- validity_months: Optional[int] = Field(None, description="Certificate validity period")
-
-
-class TrainingCourseCreate(TrainingCourseBase):
- """
- Create training course
-
- Clinical Context: Create new training program for staff
- Standards: Joint Commission training requirements, OSHA
- Performance: <200ms target
- Security: RBAC role:training_coordinator, audit_logging:yes, PHI:no
- """
- learning_objectives: Optional[List[str]] = Field(None, description="Course learning objectives")
- topics: Optional[List[str]] = Field(None, description="Topics covered")
- prerequisites: Optional[List[str]] = Field(None, description="Prerequisite courses")
-
- model_config = ConfigDict(
- json_schema_extra={
- "examples": [{
- "course_code": "BLS-2025",
- "title": "Basic Life Support (BLS) Certification",
- "description": "AHA Basic Life Support for healthcare providers",
- "training_type": "certification",
- "category": "Emergency Response",
- "delivery_method": "in_person",
- "duration_hours": 4.5,
- "is_mandatory": True,
- "is_annual": False,
- "ceu_credits": 4.5,
- "requires_exam": True,
- "passing_score": 80,
- "validity_months": 24,
- "learning_objectives": [
- "Perform high-quality CPR",
- "Use AED effectively",
- "Demonstrate relief of choking"
- ]
- }]
- }
- )
-
-
-class TrainingCourseUpdate(BaseModel):
- """Update training course"""
- title: Optional[str] = Field(None, min_length=1, max_length=200)
- description: Optional[str] = Field(None, max_length=2000)
-
- duration_hours: Optional[Decimal] = None
-
- is_mandatory: Optional[bool] = None
- is_annual: Optional[bool] = None
-
- ceu_credits: Optional[Decimal] = None
- cme_credits: Optional[Decimal] = None
-
- passing_score: Optional[Decimal] = None
- validity_months: Optional[int] = None
-
- status: Optional[CourseStatus] = None
-
-
-class TrainingCourseResponse(TrainingCourseBase):
- """
- Training course response
-
- Clinical Context: Return full course details
- Performance: <100ms target
- """
- id: UUID
- tenant_id: UUID
-
- status: CourseStatus
-
- total_enrollments: int
- total_completions: int
- average_score: Optional[Decimal]
-
- created_at: datetime
- updated_at: datetime
-
- model_config = ConfigDict(from_attributes=True)
-
-
-class TrainingCourseList(BaseModel):
- """List of training courses with pagination"""
- items: List[TrainingCourseResponse]
- total: int
- page: int = 1
- page_size: int = 50
- pages: int
-
-
-# ============================================================================
-# Training Enrollment Schemas
-# ============================================================================
-
-
-class TrainingEnrollmentBase(BaseModel):
- """Base training enrollment fields"""
- enrollment_date: date = Field(..., description="Date of enrollment")
- due_date: Optional[date] = Field(None, description="Completion due date")
-
- notes: Optional[str] = Field(None, max_length=1000, description="Enrollment notes")
-
-
-class TrainingEnrollmentCreate(TrainingEnrollmentBase):
- """
- Create training enrollment
-
- Clinical Context: Enroll staff member in training course
- Standards: Joint Commission training documentation
- Performance: <200ms target
- Security: RBAC role:training_coordinator, audit_logging:yes, PHI:no
- """
- course_id: UUID = Field(..., description="Course to enroll in")
- user_id: UUID = Field(..., description="User being enrolled")
-
- model_config = ConfigDict(
- json_schema_extra={
- "examples": [{
- "course_id": "123e4567-e89b-12d3-a456-426614174000",
- "user_id": "987fcdeb-51a2-43f7-9c6d-8e2a1b3c4d5e",
- "enrollment_date": "2025-01-01",
- "due_date": "2025-01-31",
- "notes": "Annual mandatory compliance training"
- }]
- }
- )
-
-
-class TrainingEnrollmentUpdate(BaseModel):
- """Update training enrollment"""
- status: Optional[TrainingStatus] = None
-
- started_at: Optional[datetime] = None
- completed_at: Optional[datetime] = None
-
- exam_score: Optional[Decimal] = None
- attempts: Optional[int] = None
-
- notes: Optional[str] = Field(None, max_length=1000)
-
-
-class TrainingEnrollmentResponse(TrainingEnrollmentBase):
- """
- Training enrollment response
-
- Clinical Context: Return enrollment status and progress
- Performance: <100ms target
- """
- id: UUID
- tenant_id: UUID
-
- course_id: UUID
- user_id: UUID
-
- status: TrainingStatus
-
- started_at: Optional[datetime]
- completed_at: Optional[datetime]
-
- exam_score: Optional[Decimal]
- attempts: int
- passed: bool
-
- certificate_issued: bool
- certificate_number: Optional[str]
- certificate_expiration: Optional[date]
-
- created_at: datetime
- updated_at: datetime
-
- model_config = ConfigDict(from_attributes=True)
-
-
-class TrainingEnrollmentList(BaseModel):
- """List of training enrollments with pagination"""
- items: List[TrainingEnrollmentResponse]
- total: int
- page: int = 1
- page_size: int = 50
- pages: int
-
-
-# ============================================================================
-# Competency Assessment Schemas
-# ============================================================================
-
-
-class CompetencyAssessmentBase(BaseModel):
- """Base competency assessment fields"""
- skill_name: str = Field(..., max_length=200, description="Skill being assessed")
- skill_category: str = Field(..., max_length=100, description="Skill category")
-
- assessment_date: date = Field(..., description="Date of assessment")
- assessment_method: str = Field(..., max_length=100, description="Assessment method")
-
-
-class CompetencyAssessmentCreate(CompetencyAssessmentBase):
- """
- Create competency assessment
-
- Clinical Context: Assess staff clinical competency
- Standards: Joint Commission competency assessment requirements
- Performance: <200ms target
- Security: RBAC role:clinical_supervisor, audit_logging:yes, PHI:no
- """
- user_id: UUID = Field(..., description="User being assessed")
- assessor_id: UUID = Field(..., description="Assessor performing evaluation")
-
- model_config = ConfigDict(
- json_schema_extra={
- "examples": [{
- "user_id": "987fcdeb-51a2-43f7-9c6d-8e2a1b3c4d5e",
- "assessor_id": "123e4567-e89b-12d3-a456-426614174000",
- "skill_name": "IV Catheter Insertion",
- "skill_category": "Clinical Skills",
- "assessment_date": "2025-01-15",
- "assessment_method": "Direct observation with checklist"
- }]
- }
- )
-
-
-class CompetencyAssessmentUpdate(BaseModel):
- """Update competency assessment results"""
- competency_level: Optional[CompetencyLevel] = None
- score: Optional[Decimal] = Field(None, description="Assessment score")
-
- observations: Optional[str] = Field(None, max_length=2000, description="Assessor observations")
- strengths: Optional[List[str]] = Field(None, description="Identified strengths")
- areas_for_improvement: Optional[List[str]] = Field(None, description="Areas needing development")
-
- competent: Optional[bool] = None
- remediation_required: Optional[bool] = None
-
-
-class CompetencyAssessmentResponse(CompetencyAssessmentBase):
- """
- Competency assessment response
-
- Clinical Context: Return assessment results
- Performance: <100ms target
- """
- id: UUID
- tenant_id: UUID
-
- user_id: UUID
- assessor_id: UUID
-
- competency_level: CompetencyLevel
- score: Optional[Decimal]
-
- observations: Optional[str]
- competent: bool
- remediation_required: bool
-
- valid_until: Optional[date]
-
- created_at: datetime
- updated_at: datetime
-
- model_config = ConfigDict(from_attributes=True)
-
-
-class CompetencyAssessmentList(BaseModel):
- """List of competency assessments with pagination"""
- items: List[CompetencyAssessmentResponse]
- total: int
- page: int = 1
- page_size: int = 50
- pages: int
-
-
-# ============================================================================
-# Certification Schemas
-# ============================================================================
-
-
-class CertificationBase(BaseModel):
- """Base certification fields"""
- certification_name: str = Field(..., max_length=200, description="Certification name")
- certification_type: str = Field(..., max_length=100, description="Type of certification")
-
- issuing_organization: str = Field(..., max_length=200, description="Issuing body")
- certification_number: str = Field(..., max_length=100, description="Certificate number")
-
- issue_date: date = Field(..., description="Date issued")
- expiration_date: Optional[date] = Field(None, description="Expiration date")
-
-
-class CertificationCreate(CertificationBase):
- """
- Create certification record
-
- Clinical Context: Document professional certification
- Standards: State licensure, professional certification tracking
- Performance: <200ms target
- Security: RBAC role:training_coordinator, audit_logging:yes, PHI:no
- """
- user_id: UUID = Field(..., description="User holding certification")
-
- model_config = ConfigDict(
- json_schema_extra={
- "examples": [{
- "user_id": "987fcdeb-51a2-43f7-9c6d-8e2a1b3c4d5e",
- "certification_name": "Registered Nurse (RN)",
- "certification_type": "Professional License",
- "issuing_organization": "State Board of Nursing",
- "certification_number": "RN-123456",
- "issue_date": "2020-06-15",
- "expiration_date": "2026-06-15"
- }]
- }
- )
-
-
-class CertificationUpdate(BaseModel):
- """Update certification record"""
- status: Optional[CertificationStatus] = None
- expiration_date: Optional[date] = None
-
- renewal_date: Optional[date] = None
- verification_date: Optional[date] = None
-
-
-class CertificationResponse(CertificationBase):
- """
- Certification response
-
- Clinical Context: Return certification details and status
- Performance: <100ms target
- """
- id: UUID
- tenant_id: UUID
- user_id: UUID
-
- status: CertificationStatus
-
- renewal_date: Optional[date]
- verification_date: Optional[date]
-
- created_at: datetime
- updated_at: datetime
-
- model_config = ConfigDict(from_attributes=True)
-
-
-class CertificationList(BaseModel):
- """List of certifications with pagination"""
- items: List[CertificationResponse]
- total: int
- page: int = 1
- page_size: int = 50
- pages: int
-
-
-# ============================================================================
-# Dashboard & Analytics Schemas
-# ============================================================================
-
-
-class TrainingDashboardStats(BaseModel):
- """
- Dashboard statistics
-
- Clinical Context: Training compliance and completion tracking
- Performance: <200ms target
- """
- total_active_courses: int = Field(..., description="Active training courses")
- total_enrollments: int = Field(..., description="Total current enrollments")
-
- mandatory_training_compliance: Decimal = Field(..., description="Compliance rate %")
- pending_completions: int = Field(..., description="Enrollments pending completion")
- overdue_trainings: int = Field(..., description="Overdue training assignments")
-
- certifications_expiring_30_days: int = Field(..., description="Certs expiring in 30 days")
- certifications_expired: int = Field(..., description="Expired certifications")
-
- average_completion_time: Optional[Decimal] = Field(None, description="Avg completion time (hours)")
- average_exam_score: Optional[Decimal] = Field(None, description="Avg exam score %")
-
- top_courses_by_enrollment: List[dict] = Field(default_factory=list, description="Top 10 courses")
- training_by_department: List[dict] = Field(default_factory=list, description="Training status by dept")
-
-
-class UserTrainingProfile(BaseModel):
- """
- User training profile
-
- Clinical Context: Individual staff training record
- Performance: <200ms target
- """
- user_id: UUID = Field(..., description="User identifier")
-
- completed_courses: int = Field(..., description="Total courses completed")
- pending_courses: int = Field(..., description="Courses in progress")
- overdue_courses: int = Field(..., description="Overdue assignments")
-
- total_ceu_credits: Decimal = Field(..., description="Total CEU credits earned")
- total_cme_credits: Decimal = Field(..., description="Total CME credits earned")
-
- active_certifications: int = Field(..., description="Active certifications")
- expiring_certifications: int = Field(..., description="Certifications expiring soon")
-
- competency_level_avg: Optional[Decimal] = Field(None, description="Average competency level")
-
- recent_completions: List[dict] = Field(default_factory=list, description="Recent completions")
- upcoming_due_dates: List[dict] = Field(default_factory=list, description="Upcoming deadlines")
-
-
-class ComplianceReport(BaseModel):
- """
- Training compliance report
-
- Clinical Context: Regulatory compliance tracking
- Standards: Joint Commission, OSHA, HIPAA
- Performance: <500ms target (complex aggregation)
- """
- report_date: date = Field(..., description="Report generation date")
- period_start: date = Field(..., description="Reporting period start")
- period_end: date = Field(..., description="Reporting period end")
-
- total_staff: int = Field(..., description="Total staff count")
- compliant_staff: int = Field(..., description="Fully compliant staff")
- compliance_rate: Decimal = Field(..., description="Overall compliance %")
-
- mandatory_training_compliance: Decimal = Field(..., description="Mandatory training compliance %")
- certification_compliance: Decimal = Field(..., description="Certification compliance %")
-
- non_compliant_staff: List[dict] = Field(default_factory=list, description="Staff needing action")
- overdue_trainings: List[dict] = Field(default_factory=list, description="Overdue trainings")
diff --git a/src/apps/trena/service.py b/src/apps/trena/service.py
deleted file mode 100644
index 788fb6c0ce156d9e586f8c8b6c2e6e07a4be8362..0000000000000000000000000000000000000000
--- a/src/apps/trena/service.py
+++ /dev/null
@@ -1,775 +0,0 @@
-"""
-Trena - Enhanced Healthcare Training & Skills Management Service
-Enterprise-grade training platform with TOPSIS curriculum optimization,
-AYRAD fusion for skills assessment, and comprehensive training analytics
-
-Phase 2 Intelligence Features:
-- TOPSIS-optimized curriculum planning and skills development paths
-- AYRAD fusion for complex training decisions and competency assessment
-- Predictive skills analytics and performance forecasting
-- Real-time training optimization and adaptive learning
-- Advanced certification management and compliance tracking
-- Comprehensive training performance analytics and insights
-"""
-
-from core.common.service_patterns import AsyncHealthcareService, healthcare_operation
-from core.common.imports import datetime, UTC, UUID, dataclass, Enum, Dict, List, Optional, Any
-from core.common.exceptions import ValidationException
-from core.decision.topsis import run_topsis_analysis, WeightingMethod, OptimizationMethod
-from core.services.topsis_engine import OptimizedTOPSISEngine
-from core.monitoring.resource_monitor import ResourceMonitor
-from enum import Enum
-from dataclasses import dataclass, field
-from typing import Dict, List, Optional, Any
-from datetime import datetime, timedelta
-from uuid import uuid4
-import logging
-
-logger = logging.getLogger(__name__)
-
-
-class TrainingStatus(Enum):
- """Enhanced training session status"""
- SCHEDULED = "scheduled"
- IN_PROGRESS = "in_progress"
- COMPLETED = "completed"
- CANCELLED = "cancelled"
- POSTPONED = "postponed"
- OPTIMIZATION_ANALYSIS = "optimization_analysis"
- ASSESSMENT_PENDING = "assessment_pending"
- CERTIFICATION_REVIEW = "certification_review"
-
-
-class CompetencyLevel(Enum):
- """Enhanced staff competency levels"""
- NOVICE = "novice"
- BEGINNER = "beginner"
- COMPETENT = "competent"
- PROFICIENT = "proficient"
- EXPERT = "expert"
- MASTER = "master"
- SPECIALIST = "specialist"
-
-
-class TrainingType(Enum):
- """Enhanced types of training programs"""
- ORIENTATION = "orientation"
- CLINICAL_SKILLS = "clinical_skills"
- SAFETY_TRAINING = "safety_training"
- COMPLIANCE = "compliance"
- CONTINUING_EDUCATION = "continuing_education"
- CERTIFICATION = "certification"
- LEADERSHIP = "leadership"
- SPECIALTY = "specialty"
- EMERGENCY_RESPONSE = "emergency_response"
- QUALITY_IMPROVEMENT = "quality_improvement"
- RESEARCH_METHODS = "research_methods"
-
-
-class AssessmentType(Enum):
- """Enhanced types of competency assessments"""
- WRITTEN_TEST = "written_test"
- PRACTICAL_DEMO = "practical_demo"
- SIMULATION = "simulation"
- OBSERVATION = "observation"
- PEER_REVIEW = "peer_review"
- PORTFOLIO_REVIEW = "portfolio_review"
- CASE_STUDY = "case_study"
-
-
-class Priority(Enum):
- """Training priority levels"""
- LOW = "low"
- NORMAL = "normal"
- HIGH = "high"
- URGENT = "urgent"
- CRITICAL = "critical"
- MANDATORY = "mandatory"
-
-
-class OptimizationStrategy(Enum):
- """Training optimization strategies"""
- SKILL_DEVELOPMENT = "skill_development"
- COMPLIANCE_MAXIMIZATION = "compliance_maximization"
- COST_MINIMIZATION = "cost_minimization"
- TIME_EFFICIENCY = "time_efficiency"
- COMPETENCY_ADVANCEMENT = "competency_advancement"
-
-
-@dataclass
-class TrainingCriteria:
- """Training decision criteria with Phase 2 intelligence"""
- learning_objectives: List[str]
- skill_requirements: Dict[str, CompetencyLevel]
- time_constraints: Dict[str, Any]
- budget_limitations: Dict[str, float]
- compliance_requirements: List[str]
- priority_level: Priority
- target_competency: CompetencyLevel
- topsis_weight: float = 1.0
- ayrad_priority: float = 1.0
-
-
-@dataclass
-class TrainingAlternative:
- """Enhanced training alternative with TOPSIS/AYRAD integration"""
- training_id: str
- training_name: str
- training_type: TrainingType
- duration: timedelta
- cost: float
- delivery_method: str
- competency_target: CompetencyLevel
- prerequisites: List[str]
- effectiveness_score: float
- flexibility_rating: float
- topsis_score: float = 0.0
- suitability_score: float = 0.0
-
-
-@dataclass
-class SkillsAssessment:
- """Enhanced skills assessment result"""
- assessment_id: str
- trainee_id: str
- skill_area: str
- assessment_type: AssessmentType
- current_level: CompetencyLevel
- target_level: CompetencyLevel
- score: float
- strengths: List[str]
- improvement_areas: List[str]
- topsis_development_score: float = 0.0
- ayrad_recommendation: Optional[str] = None
- predicted_advancement_time: Optional[timedelta] = None
-
-
-@dataclass
-class CurriculumOptimization:
- """Curriculum optimization configuration"""
- optimization_id: str = field(default_factory=lambda: str(uuid4()))
- strategy: OptimizationStrategy = OptimizationStrategy.SKILL_DEVELOPMENT
- target_competency_improvement: float = 0.25
- compliance_threshold: float = 0.95
- budget_limit: Optional[float] = None
- timeline_constraint: Optional[timedelta] = None
- learning_constraints: Dict[str, Any] = field(default_factory=dict)
-
-
-@dataclass
-class TrainingDashboard:
- """Training analytics dashboard data"""
- training_metrics: Dict[str, Any] = field(default_factory=dict)
- competency_analytics: Dict[str, Any] = field(default_factory=dict)
- optimization_insights: List[Dict[str, Any]] = field(default_factory=list)
- compliance_tracking: Dict[str, Any] = field(default_factory=dict)
- performance_trends: Dict[str, Any] = field(default_factory=dict)
- certification_status: Dict[str, Any] = field(default_factory=dict)
- generated_at: datetime = field(default_factory=datetime.now)
-
-
-class TrenaService(AsyncHealthcareService):
- """
- Enhanced Healthcare Training Service with Phase 2 Intelligence
-
- Provides TOPSIS-optimized curriculum planning, AYRAD fusion for skills assessment,
- and comprehensive training analytics for healthcare education.
-
- Features:
- - TOPSIS multi-criteria curriculum optimization
- - AYRAD fusion for complex training decisions
- - Predictive competency and performance analytics
- - Real-time training monitoring and optimization
- - Advanced skills assessment and certification tracking
- - Comprehensive training performance analytics
- """
-
- def __init__(self):
- super().__init__("trena")
- # Using TOPSIS engine directly for decision support (see topsis_engine.py)
- self.resource_monitor = ResourceMonitor()
-
- # Training decision weights for TOPSIS analysis
- self.curriculum_weights = {
- 'effectiveness_score': 0.30,
- 'cost_efficiency': 0.20,
- 'time_efficiency': 0.25,
- 'flexibility_rating': 0.15,
- 'compliance_match': 0.10
- }
-
- # Training-specific configurations
- self.training_thresholds = {
- 'competency_minimum': 0.80,
- 'compliance_required': 0.95,
- 'effectiveness_target': 0.85,
- 'budget_efficiency': 0.75,
- 'completion_rate_minimum': 0.90,
- 'assessment_accuracy': 0.88
- }
-
- # Performance tracking
- self._training_cache = {}
- self._optimization_history = []
-
- @healthcare_operation
- async def optimize_curriculum_plan(
- self,
- criteria: TrainingCriteria,
- training_alternatives: List[TrainingAlternative],
- optimization_config: Optional[CurriculumOptimization] = None
- ) -> Dict[str, Any]:
- """
- TOPSIS-optimized curriculum planning with AYRAD fusion
-
- Args:
- criteria: Training decision criteria
- training_alternatives: Available training alternatives
- optimization_config: Optimization configuration
-
- Returns:
- Optimized curriculum plan with TOPSIS recommendations
- """
- try:
- if not training_alternatives:
- raise ValidationException("No training alternatives provided")
-
- # Prepare TOPSIS analysis matrix
- alternatives_matrix = []
- for training in training_alternatives:
- alternatives_matrix.append([
- training.effectiveness_score,
- 1 / training.cost if training.cost > 0 else 0, # Cost efficiency (lower cost is better)
- 1 / training.duration.total_seconds() if training.duration else 0, # Time efficiency
- training.flexibility_rating,
- self._calculate_compliance_match(training, criteria)
- ])
-
- # Execute TOPSIS analysis for curriculum optimization
- topsis_result = run_topsis_analysis(
- alternatives_matrix=alternatives_matrix,
- weights=list(self.curriculum_weights.values()),
- weighting_method=WeightingMethod.DIRECT,
- optimization_method=OptimizationMethod.BALANCED
- )
-
- # Enhanced analysis with AYRAD fusion
- ayrad_context = {
- 'domain': 'healthcare_training',
- 'learning_objectives': criteria.learning_objectives,
- 'skill_requirements': {k: v.value for k, v in criteria.skill_requirements.items()},
- 'priority_level': criteria.priority_level.value,
- 'target_competency': criteria.target_competency.value
- }
-
- ayrad_enhancement = await self.ayrad_fusion.enhance_decision(
- topsis_result, ayrad_context
- )
-
- # Build optimized curriculum
- optimized_curriculum = await self._build_curriculum_plan(
- training_alternatives, topsis_result, ayrad_enhancement, criteria, optimization_config
- )
-
- # Cache optimization result
- cache_key = f"curriculum_opt_{datetime.now().isoformat()}"
- self._training_cache[cache_key] = optimized_curriculum
-
- # Track optimization history
- self._optimization_history.append({
- 'timestamp': datetime.now(),
- 'alternatives_analyzed': len(training_alternatives),
- 'topsis_scores': topsis_result.get('scores', []),
- 'recommended_training': topsis_result.get('best_alternative', 0),
- 'optimization_strategy': optimization_config.strategy if optimization_config else 'default'
- })
-
- logger.info(f"Curriculum plan optimized with {len(training_alternatives)} alternatives")
- return optimized_curriculum
-
- except Exception as e:
- logger.error(f"Curriculum optimization failed: {str(e)}")
- raise ValidationException(f"Curriculum optimization failed: {str(e)}")
-
- @healthcare_operation
- async def assess_competency_skills(
- self,
- trainee_id: str,
- skill_area: str,
- assessment_type: AssessmentType,
- assessment_data: Dict[str, Any]
- ) -> SkillsAssessment:
- """
- TOPSIS-enhanced competency assessment with predictive insights
-
- Args:
- trainee_id: Trainee identifier
- skill_area: Area of skills being assessed
- assessment_type: Type of assessment
- assessment_data: Assessment results and data
-
- Returns:
- Enhanced skills assessment with TOPSIS scoring and predictions
- """
- try:
- # Extract competency metrics for TOPSIS analysis
- competency_metrics = self._extract_competency_metrics(assessment_data)
-
- # TOPSIS analysis for competency assessment
- if len(competency_metrics) >= 5:
- competency_weights = [0.25, 0.20, 0.20, 0.15, 0.20] # Knowledge, skills, application, consistency, improvement
-
- topsis_result = run_topsis_analysis(
- alternatives_matrix=[competency_metrics[:5]],
- weights=competency_weights,
- weighting_method=WeightingMethod.ENTROPY,
- optimization_method=OptimizationMethod.CONSERVATIVE
- )
- topsis_development_score = topsis_result.get('scores', [0])[0] if topsis_result.get('scores') else 0
- else:
- topsis_development_score = sum(competency_metrics) / len(competency_metrics) if competency_metrics else 0.7
-
- # AYRAD fusion for competency insights
- ayrad_context = {
- 'trainee_profile': {'id': trainee_id, 'skill_area': skill_area},
- 'assessment_data': assessment_data,
- 'assessment_type': assessment_type.value,
- 'development_score': topsis_development_score
- }
-
- competency_insights = await self.ayrad_fusion.generate_insights(ayrad_context)
-
- # Determine current and target competency levels
- current_level = self._determine_competency_level(topsis_development_score, assessment_data)
- target_level = self._suggest_target_level(current_level, topsis_development_score)
-
- # Calculate overall score and identify strengths/improvements
- overall_score = topsis_development_score * 100
- strengths, improvement_areas = self._analyze_competency_gaps(assessment_data, topsis_development_score)
-
- # Predict advancement timeline
- advancement_time = self._predict_competency_advancement(
- current_level, target_level, topsis_development_score, assessment_data
- )
-
- # Generate skills assessment result
- assessment_result = SkillsAssessment(
- assessment_id=str(uuid4()),
- trainee_id=trainee_id,
- skill_area=skill_area,
- assessment_type=assessment_type,
- current_level=current_level,
- target_level=target_level,
- score=overall_score,
- strengths=strengths,
- improvement_areas=improvement_areas,
- topsis_development_score=topsis_development_score,
- ayrad_recommendation=competency_insights.get('recommendation'),
- predicted_advancement_time=advancement_time
- )
-
- logger.info(f"Competency assessment completed for trainee {trainee_id} in {skill_area}")
- return assessment_result
-
- except Exception as e:
- logger.error(f"Competency assessment failed: {str(e)}")
- raise ValidationException(f"Competency assessment failed: {str(e)}")
-
- @healthcare_operation
- async def get_training_dashboard(
- self,
- time_period: Optional[str] = "30d",
- include_predictions: bool = True
- ) -> TrainingDashboard:
- """
- Generate comprehensive training analytics dashboard
-
- Args:
- time_period: Analysis time period (7d, 30d, 90d)
- include_predictions: Include predictive analytics
-
- Returns:
- Training dashboard with analytics and insights
- """
- try:
- # Training metrics
- training_metrics = await self._get_training_metrics(time_period)
-
- # Competency analytics
- competency_analytics = await self._get_competency_analytics(time_period)
-
- # Optimization insights
- optimization_insights = await self._get_optimization_insights(time_period)
-
- # Compliance tracking
- compliance_tracking = await self._get_compliance_tracking(time_period)
-
- # Performance trends
- performance_trends = await self._get_performance_trends(time_period)
-
- # Certification status
- certification_status = await self._get_certification_status()
-
- dashboard = TrainingDashboard(
- training_metrics=training_metrics,
- competency_analytics=competency_analytics,
- optimization_insights=optimization_insights,
- compliance_tracking=compliance_tracking,
- performance_trends=performance_trends,
- certification_status=certification_status
- )
-
- logger.info(f"Training dashboard generated for period: {time_period}")
- return dashboard
-
- except Exception as e:
- logger.error(f"Training dashboard generation failed: {str(e)}")
- raise ValidationException(f"Dashboard generation failed: {str(e)}")
-
- # Legacy compatibility methods
- async def create_training_session(self, *args, **kwargs):
- """Legacy method - redirects to optimize_curriculum_plan"""
- return await self.optimize_curriculum_plan(*args, **kwargs)
-
- async def assess_competency(self, *args, **kwargs):
- """Legacy method - redirects to assess_competency_skills"""
- return await self.assess_competency_skills(*args, **kwargs)
-
- async def get_training_analytics(self, *args, **kwargs):
- """Legacy method - redirects to get_training_dashboard"""
- dashboard = await self.get_training_dashboard(*args, **kwargs)
- return {
- 'training_data': dashboard.training_metrics,
- 'competency_data': dashboard.competency_analytics,
- 'generated_at': dashboard.generated_at
- }
-
- # Private helper methods
- def _calculate_compliance_match(self, training: TrainingAlternative, criteria: TrainingCriteria) -> float:
- """Calculate how well training matches compliance requirements"""
- if not criteria.compliance_requirements:
- return 1.0
-
- training_compliance_areas = [
- training.training_type.value,
- 'general_compliance' if training.training_type in [TrainingType.COMPLIANCE, TrainingType.SAFETY_TRAINING] else 'specific'
- ]
-
- matches = 0
- for requirement in criteria.compliance_requirements:
- if any(req.lower() in area.lower() for area in training_compliance_areas for req in [requirement]):
- matches += 1
-
- return matches / len(criteria.compliance_requirements)
-
- def _extract_competency_metrics(self, assessment_data: Dict[str, Any]) -> List[float]:
- """Extract numerical competency metrics from assessment data"""
- metrics = []
-
- # Extract common competency metrics
- if 'knowledge_score' in assessment_data:
- metrics.append(float(assessment_data['knowledge_score']) / 100)
- if 'practical_skills' in assessment_data:
- metrics.append(float(assessment_data['practical_skills']) / 100)
- if 'application_ability' in assessment_data:
- metrics.append(float(assessment_data['application_ability']) / 100)
- if 'consistency_rating' in assessment_data:
- metrics.append(float(assessment_data['consistency_rating']) / 100)
- if 'improvement_rate' in assessment_data:
- metrics.append(float(assessment_data['improvement_rate']) / 100)
-
- return metrics or [0.75, 0.70, 0.80, 0.75, 0.65] # Default metrics if none found
-
- def _determine_competency_level(self, topsis_score: float, assessment_data: Dict[str, Any]) -> CompetencyLevel:
- """Determine competency level based on TOPSIS score and assessment data"""
- if topsis_score >= 0.90:
- return CompetencyLevel.EXPERT
- elif topsis_score >= 0.80:
- return CompetencyLevel.PROFICIENT
- elif topsis_score >= 0.70:
- return CompetencyLevel.COMPETENT
- elif topsis_score >= 0.60:
- return CompetencyLevel.BEGINNER
- else:
- return CompetencyLevel.NOVICE
-
- def _suggest_target_level(self, current_level: CompetencyLevel, topsis_score: float) -> CompetencyLevel:
- """Suggest target competency level based on current level and potential"""
- level_progression = {
- CompetencyLevel.NOVICE: CompetencyLevel.BEGINNER,
- CompetencyLevel.BEGINNER: CompetencyLevel.COMPETENT,
- CompetencyLevel.COMPETENT: CompetencyLevel.PROFICIENT,
- CompetencyLevel.PROFICIENT: CompetencyLevel.EXPERT,
- CompetencyLevel.EXPERT: CompetencyLevel.MASTER
- }
-
- if topsis_score >= 0.85: # High potential - can skip levels
- advanced_progression = {
- CompetencyLevel.NOVICE: CompetencyLevel.COMPETENT,
- CompetencyLevel.BEGINNER: CompetencyLevel.PROFICIENT,
- CompetencyLevel.COMPETENT: CompetencyLevel.EXPERT,
- CompetencyLevel.PROFICIENT: CompetencyLevel.MASTER,
- CompetencyLevel.EXPERT: CompetencyLevel.SPECIALIST
- }
- return advanced_progression.get(current_level, CompetencyLevel.EXPERT)
-
- return level_progression.get(current_level, current_level)
-
- def _analyze_competency_gaps(self, assessment_data: Dict[str, Any], topsis_score: float) -> tuple:
- """Analyze competency strengths and improvement areas"""
- strengths = []
- improvement_areas = []
-
- # Analyze based on assessment data
- for area, score in assessment_data.items():
- if isinstance(score, (int, float)):
- normalized_score = score / 100 if score > 1 else score
- if normalized_score >= 0.8:
- strengths.append(area.replace('_', ' ').title())
- elif normalized_score < 0.6:
- improvement_areas.append(area.replace('_', ' ').title())
-
- # Default analysis if no specific data
- if not strengths and not improvement_areas:
- if topsis_score >= 0.8:
- strengths = ["Strong foundational knowledge", "Good practical application"]
- improvement_areas = ["Advanced techniques", "Leadership skills"]
- else:
- strengths = ["Basic understanding", "Willingness to learn"]
- improvement_areas = ["Practical skills", "Consistency", "Knowledge depth"]
-
- return strengths, improvement_areas
-
- def _predict_competency_advancement(
- self,
- current_level: CompetencyLevel,
- target_level: CompetencyLevel,
- topsis_score: float,
- assessment_data: Dict[str, Any]
- ) -> Optional[timedelta]:
- """Predict time required for competency advancement"""
- level_gaps = {
- (CompetencyLevel.NOVICE, CompetencyLevel.BEGINNER): 30,
- (CompetencyLevel.BEGINNER, CompetencyLevel.COMPETENT): 45,
- (CompetencyLevel.COMPETENT, CompetencyLevel.PROFICIENT): 60,
- (CompetencyLevel.PROFICIENT, CompetencyLevel.EXPERT): 90,
- (CompetencyLevel.EXPERT, CompetencyLevel.MASTER): 120
- }
-
- base_days = level_gaps.get((current_level, target_level), 60)
-
- # Adjust based on TOPSIS score (higher score = faster advancement)
- score_multiplier = 2.0 - topsis_score # Range: 1.0 - 2.0
-
- # Adjust based on learning rate indicator
- learning_rate = assessment_data.get('improvement_rate', 50) / 100
- learning_multiplier = 2.0 - learning_rate
-
- adjusted_days = int(base_days * score_multiplier * learning_multiplier)
- return timedelta(days=adjusted_days)
-
- async def _build_curriculum_plan(
- self,
- training_alternatives: List[TrainingAlternative],
- topsis_result: Dict[str, Any],
- ayrad_enhancement: Dict[str, Any],
- criteria: TrainingCriteria,
- optimization_config: Optional[CurriculumOptimization]
- ) -> Dict[str, Any]:
- """Build optimized curriculum plan"""
- best_training_index = topsis_result.get('best_alternative', 0)
- best_training = training_alternatives[best_training_index]
-
- return {
- 'curriculum_id': str(uuid4()),
- 'recommended_training': {
- 'training_id': best_training.training_id,
- 'training_name': best_training.training_name,
- 'training_type': best_training.training_type.value,
- 'topsis_score': topsis_result.get('scores', [0])[best_training_index],
- 'duration': str(best_training.duration),
- 'cost': best_training.cost,
- 'delivery_method': best_training.delivery_method,
- 'target_competency': best_training.competency_target.value
- },
- 'optimization_strategy': optimization_config.strategy if optimization_config else OptimizationStrategy.SKILL_DEVELOPMENT,
- 'ayrad_insights': ayrad_enhancement,
- 'training_rankings': [
- {
- 'rank': i + 1,
- 'training_id': training.training_id,
- 'topsis_score': topsis_result.get('scores', [0])[i] if i < len(topsis_result.get('scores', [])) else 0,
- 'suitability_reason': self._get_training_suitability_reason(topsis_result.get('scores', [0])[i] if i < len(topsis_result.get('scores', [])) else 0)
- }
- for i, training in enumerate(training_alternatives)
- ],
- 'learning_path': {
- 'prerequisites': best_training.prerequisites,
- 'learning_objectives': criteria.learning_objectives,
- 'milestones': self._generate_learning_milestones(best_training, criteria),
- 'assessment_schedule': self._generate_assessment_schedule(best_training)
- }
- }
-
- def _get_training_suitability_reason(self, topsis_score: float) -> str:
- """Get training suitability reason based on TOPSIS score"""
- if topsis_score >= 0.8:
- return "Excellent fit for learning objectives and constraints"
- elif topsis_score >= 0.6:
- return "Good match with minor adjustments needed"
- elif topsis_score >= 0.4:
- return "Acceptable option with some limitations"
- else:
- return "Limited suitability, consider alternative approaches"
-
- def _generate_learning_milestones(self, training: TrainingAlternative, criteria: TrainingCriteria) -> List[Dict[str, Any]]:
- """Generate learning milestones for the training program"""
- total_duration = training.duration
- milestones = []
-
- milestone_percentages = [0.25, 0.50, 0.75, 1.0]
- milestone_names = ["Foundation Established", "Skills Development", "Application Practice", "Competency Achieved"]
-
- for i, (percentage, name) in enumerate(zip(milestone_percentages, milestone_names)):
- milestone_date = datetime.now() + timedelta(seconds=total_duration.total_seconds() * percentage)
- milestones.append({
- 'milestone_id': i + 1,
- 'name': name,
- 'target_date': milestone_date,
- 'completion_percentage': percentage * 100,
- 'competency_checkpoint': self._map_milestone_to_competency(percentage, training.competency_target)
- })
-
- return milestones
-
- def _generate_assessment_schedule(self, training: TrainingAlternative) -> List[Dict[str, Any]]:
- """Generate assessment schedule for the training"""
- assessments = []
-
- # Initial assessment
- assessments.append({
- 'assessment_type': AssessmentType.WRITTEN_TEST.value,
- 'timing': 'Week 1',
- 'purpose': 'Baseline assessment'
- })
-
- # Mid-term assessment
- if training.duration.days > 14:
- assessments.append({
- 'assessment_type': AssessmentType.PRACTICAL_DEMO.value,
- 'timing': f'Week {training.duration.days // 14}',
- 'purpose': 'Progress evaluation'
- })
-
- # Final assessment
- assessments.append({
- 'assessment_type': AssessmentType.SIMULATION.value,
- 'timing': f'Week {training.duration.days // 7}',
- 'purpose': 'Competency certification'
- })
-
- return assessments
-
- def _map_milestone_to_competency(self, percentage: float, target_level: CompetencyLevel) -> str:
- """Map milestone percentage to expected competency level"""
- if percentage <= 0.25:
- return "Foundation knowledge acquired"
- elif percentage <= 0.50:
- return "Basic skills demonstrated"
- elif percentage <= 0.75:
- return "Intermediate proficiency shown"
- else:
- return f"Target competency level: {target_level.value}"
-
- async def _get_training_metrics(self, time_period: str) -> Dict[str, Any]:
- """Get training performance metrics"""
- return {
- 'total_training_sessions': 156,
- 'completion_rate': 0.92,
- 'average_score': 87.3,
- 'competency_advancement_rate': 0.78,
- 'training_efficiency': 0.85,
- 'resource_utilization': 0.82,
- 'cost_per_trainee': 2850,
- 'satisfaction_score': 0.89
- }
-
- async def _get_competency_analytics(self, time_period: str) -> Dict[str, Any]:
- """Get competency development analytics"""
- return {
- 'competency_distribution': {
- 'novice': 0.12,
- 'beginner': 0.25,
- 'competent': 0.35,
- 'proficient': 0.20,
- 'expert': 0.08
- },
- 'skills_improvement_rate': 0.24,
- 'assessment_accuracy': 0.91,
- 'competency_gap_closure': 0.68,
- 'advancement_success_rate': 0.83
- }
-
- async def _get_optimization_insights(self, time_period: str) -> List[Dict[str, Any]]:
- """Get training optimization insights"""
- return [
- {
- 'insight_type': 'curriculum_optimization',
- 'description': 'Clinical skills training showing 20% efficiency improvement potential',
- 'recommended_action': 'Implement TOPSIS-optimized skill progression',
- 'estimated_impact': 0.20,
- 'priority': 'high'
- },
- {
- 'insight_type': 'competency_acceleration',
- 'description': 'Personalized learning paths could reduce training time by 25%',
- 'recommended_action': 'Deploy AYRAD-powered adaptive learning',
- 'estimated_impact': 0.25,
- 'priority': 'high'
- }
- ]
-
- async def _get_compliance_tracking(self, time_period: str) -> Dict[str, Any]:
- """Get compliance tracking data"""
- return {
- 'overall_compliance_rate': 0.96,
- 'mandatory_training_completion': 0.98,
- 'certification_renewal_rate': 0.94,
- 'regulatory_requirement_adherence': 0.97,
- 'documentation_completeness': 0.93,
- 'audit_readiness_score': 0.91
- }
-
- async def _get_performance_trends(self, time_period: str) -> Dict[str, Any]:
- """Get training performance trends"""
- return {
- 'completion_rate_trend': 0.03, # 3% improvement
- 'competency_improvement_trend': 0.05, # 5% improvement
- 'satisfaction_trend': 0.02, # 2% improvement
- 'cost_efficiency_trend': -0.08, # 8% cost reduction
- 'time_to_competency_trend': -0.12, # 12% faster achievement
- 'retention_rate_trend': 0.06 # 6% better retention
- }
-
- async def _get_certification_status(self) -> Dict[str, Any]:
- """Get certification status information"""
- return {
- 'active_certifications': 1247,
- 'pending_renewals': 89,
- 'expired_certifications': 23,
- 'new_certifications_this_period': 156,
- 'certification_compliance_rate': 0.95,
- 'average_certification_duration': 24, # months
- 'certification_success_rate': 0.91
- }
-
-
-# Singleton instance
-_trena_service_instance = None
-
-def get_trena_service() -> TrenaService:
- """Get singleton instance of TrenaService"""
- global _trena_service_instance
- if _trena_service_instance is None:
- _trena_service_instance = TrenaService()
- return _trena_service_instance
\ No newline at end of file
diff --git a/src/compliance/audit_middleware.py b/src/compliance/audit_middleware.py
index 94218c3a09f46939c58d1ca04e1f199b0a23b45a..06b4879c318556b0c9d87496cc2e04200d5ab5ed 100644
--- a/src/compliance/audit_middleware.py
+++ b/src/compliance/audit_middleware.py
@@ -221,7 +221,7 @@ class AuditMiddleware(BaseHTTPMiddleware):
"""Extract application name from path"""
apps = [
"surgio", "clinica", "educa", "insura", "movio",
- "banko", "hospi", "stoka", "campo", "trena",
+ "banko", "hospi", "stoka", "campo",
"pharma", "labo", "fabrica"
]
diff --git a/src/core/microservices/service_manager.py b/src/core/microservices/service_manager.py
index a6e2c7a67fa59010fa2c0456474800d34ffdeb23..568aa7b0874381d9b41439d83b9d2994d2242ff1 100644
--- a/src/core/microservices/service_manager.py
+++ b/src/core/microservices/service_manager.py
@@ -29,7 +29,6 @@ class ServiceType(Enum):
STOKA = "stoka" # Inventory management
FABRICA = "fabrica" # Manufacturing/supplies
CAMPO = "campo" # Field operations
- TRENA = "trena" # Training management
# Infrastructure services
AUTH_SERVICE = "auth-service"
diff --git a/src/core/routing/__init__.py b/src/core/routing/__init__.py
index 1e2f6b24ccccfbcceef4f7e87c43906b645e96ad..48b3863271fc67806d04d0d6ab3c12ae1f6928fb 100644
--- a/src/core/routing/__init__.py
+++ b/src/core/routing/__init__.py
@@ -152,7 +152,6 @@ def setup_healthcare_routers():
"movio", # Medical Logistics
"banko", # Healthcare Banking
"campo", # Field Operations
- "trena", # Training & Development
"stoka", # Storage & Inventory
"hospi", # Hospital Management
"lodger", # Facility Management
diff --git a/src/core/security/rbac.py b/src/core/security/rbac.py
index 8d132520a8357946b0b6d4988287d59d2c61455b..8d35981b25fb94a84ad24ded785cf54762f232c1 100644
--- a/src/core/security/rbac.py
+++ b/src/core/security/rbac.py
@@ -50,7 +50,6 @@ class Module(str, Enum):
BANKO = "banko" # Financial management
LODGER = "lodger" # Accommodation
FABRICA = "fabrica" # Manufacturing
- TRENA = "trena" # Training coordination
# Platform Services
ADMIN = "admin" # Platform administration
diff --git a/src/factory.py b/src/factory.py
index deda5292a7a2fc6f55029340c2e4437606499bab..6c62ef5a0e49fb4a9c0c4270b63b94ae34e0926d 100755
--- a/src/factory.py
+++ b/src/factory.py
@@ -533,10 +533,15 @@ def _setup_middleware(app: FastAPI) -> None:
TenantContextMiddleware,
require_tenant=settings.is_production(),
public_paths=[
+ "/$", # Root path exact match only
"/health", "/ready", "/live", "/metrics",
"/docs", "/redoc", "/openapi.json",
"/api/v1/auth/login", "/api/v1/auth/register",
- "/api/v1/auth/refresh", "/static"
+ "/api/v1/auth/refresh",
+ "/static",
+ "/apps", # All app UI pages
+ "/favicon",
+ "/index"
]
)
logger.info("โ
Multi-tenancy context middleware enabled (Sprint 33)")
@@ -620,6 +625,12 @@ def _setup_fallback_middleware(app: FastAPI) -> None:
response.headers["X-Process-Time"] = str(round(process_time * 1000, 2))
response.headers["X-Powered-By"] = f"YAZ Care Platform {settings.app.version}"
+ # Add no-cache headers for HTML responses in development
+ if not settings.is_production() and "text/html" in response.headers.get("content-type", ""):
+ response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, max-age=0"
+ response.headers["Pragma"] = "no-cache"
+ response.headers["Expires"] = "0"
+
return response
# 3. Core performance optimizations
@@ -788,7 +799,10 @@ def _setup_static_and_templates(app: FastAPI) -> None:
# Check if beautiful base.html exists in this directory (HIGHEST PRIORITY)
base_file = templates_dir / "base.html"
if base_file.exists():
+ # Enable auto_reload for development to prevent caching
app.state.templates = Jinja2Templates(directory=str(templates_dir))
+ app.state.templates.env.auto_reload = True
+ app.state.templates.env.cache_size = 0
logger.info("โ
Beautiful UI templates found with base.html: %s", templates_dir)
# Verify it's your beautiful template by checking size
@@ -803,6 +817,8 @@ def _setup_static_and_templates(app: FastAPI) -> None:
index_file = templates_dir / "index.html"
if index_file.exists():
app.state.templates = Jinja2Templates(directory=str(templates_dir))
+ app.state.templates.env.auto_reload = True
+ app.state.templates.env.cache_size = 0
logger.info("โ Templates with index.html: %s", templates_dir)
templates_found = True
break
diff --git a/src/middleware/tenant_context.py b/src/middleware/tenant_context.py
index 6898490a5929d63d768d03a0b523d64e5f0f9e18..dfc5fd4d2f9257b88ffcaaf415a99764a7d3de53 100644
--- a/src/middleware/tenant_context.py
+++ b/src/middleware/tenant_context.py
@@ -69,7 +69,11 @@ class TenantContextMiddleware(BaseHTTPMiddleware):
"/api/v1/auth/login",
"/api/v1/auth/register",
"/api/v1/auth/refresh",
- "/static"
+ "/static",
+ "/apps",
+ "/favicon",
+ "/index",
+ "/$" # Only exact root path
]
async def dispatch(self, request: Request, call_next: Callable) -> Response:
@@ -189,7 +193,15 @@ class TenantContextMiddleware(BaseHTTPMiddleware):
def _is_public_path(self, path: str) -> bool:
"""Check if path is public (no tenant required)."""
- return any(path.startswith(public_path) for public_path in self.public_paths)
+ # Exact match for root path
+ if path == "/" and "/$" in self.public_paths:
+ return True
+ # Prefix match for all other paths (excluding root-only marker)
+ return any(
+ path.startswith(public_path)
+ for public_path in self.public_paths
+ if public_path != "/$"
+ )
def get_current_tenant() -> Optional[str]:
diff --git a/src/routes.py b/src/routes.py
index c47220f9831a3e5644bb1c1aa5ba5609eff4b2ac..e6c3a4bada193516a932cb5bf46dbd1bbe3f0a83 100644
--- a/src/routes.py
+++ b/src/routes.py
@@ -110,7 +110,7 @@ async def logout() -> RedirectResponse:
@router.get("/apps/{app_name}", response_class=HTMLResponse)
async def app_page(request: Request, app_name: str) -> HTMLResponse:
- """Generic app page handler with dynamic branding"""
+ """Generic app page handler with dynamic branding - uses specific app templates"""
app_configs = {
"surgio": {"title": "Surgio", "full_title": "Surgio - Surgical Management", "icon": "๐ช"},
@@ -120,7 +120,12 @@ async def app_page(request: Request, app_name: str) -> HTMLResponse:
"banko": {"title": "Banko", "full_title": "Banko - Financial Management", "icon": "๐ฆ"},
"educa": {"title": "Educa", "full_title": "Educa - Medical Education", "icon": "๐"},
"pharma": {"title": "Pharma", "full_title": "Pharma - Pharmacy Operations", "icon": "๐"},
- "labo": {"title": "Labo", "full_title": "Labo - Laboratory Systems", "icon": "๐ฌ"}
+ "labo": {"title": "Labo", "full_title": "Labo - Laboratory Systems", "icon": "๐ฌ"},
+ "hospi": {"title": "Hospi", "full_title": "Hospi - Hospital Management", "icon": "๐ฅ"},
+ "campo": {"title": "Campo", "full_title": "Campo - Field Operations", "icon": "๐"},
+ "lodger": {"title": "Lodger", "full_title": "Lodger - Lodging Management", "icon": "๐จ"},
+ "fabrica": {"title": "Fabrica", "full_title": "Fabrica - Manufacturing", "icon": "๐ญ"},
+ "stoka": {"title": "Stoka", "full_title": "Stoka - Stock Management", "icon": "๐ฆ"}
}
if app_name not in app_configs:
@@ -135,7 +140,11 @@ async def app_page(request: Request, app_name: str) -> HTMLResponse:
"user": None
}
- return templates.TemplateResponse("apps/generic.html", context)
+ # Use specific app template (e.g., apps/surgio.html) if it exists, otherwise use generic
+ try:
+ return templates.TemplateResponse(f"apps/{app_name}.html", context)
+ except Exception:
+ return templates.TemplateResponse("apps/generic.html", context)
@router.get("/api/apps/{app_name}/data")
async def app_data_api(app_name: str, limit: int = 50) -> Dict[str, Any]:
diff --git a/src/shared/services/__init__.py b/src/shared/services/__init__.py
index da35735d7620762bdc6ae6d7cfe87372c238a87a..8d8323a91c5029c03b1d535f59d33c6580db63cc 100755
--- a/src/shared/services/__init__.py
+++ b/src/shared/services/__init__.py
@@ -290,8 +290,7 @@ class InsuraService(BaseService):
pass
-class MovitService(BaseService):
- """Movit application service base"""
+# MovitService removed - functionality consolidated into MovioService and StokaService
pass
diff --git a/src/ui/templates/apps/_standardized_template.html b/src/ui/templates/apps/_standardized_template.html
new file mode 100644
index 0000000000000000000000000000000000000000..76bdb9074fd809985849350a45cf10b0ecb42caf
--- /dev/null
+++ b/src/ui/templates/apps/_standardized_template.html
@@ -0,0 +1,205 @@
+{% extends "shared/app_base.html" %}
+
+{% block title %}{{ app_config.name }} - {{ app_config.description }}{% endblock %}
+
+{#
+STANDARDIZED APP TEMPLATE
+This template follows YAZ Care Platform UI/UX best practices
+
+Required: Define app_config, app_tabs, and stats in your app-specific template
+
+Example usage:
+{% set app_config = {
+'slug': 'myapp',
+'name': 'MyApp',
+'description': 'App Description',
+'entity_name': 'Entity',
+'icon': '๐ฏ',
+'gradient_from': '#3b82f6',
+'gradient_to': '#1d4ed8'
+} %}
+#}
+
+{% block dashboard_content %}
+
+{% include 'components/action_buttons.html' with app_config=app_config %}
+
+
+{% include 'components/search_filter.html' with app_config=app_config %}
+
+
+{% include 'components/data_table.html' with app_config=app_config %}
+{% endblock %}
+
+{% block additional_tabs %}
+
+
+
+
+
+ All {{ app_config.entity_name }}s
+
+
+
+
+
+
+
+
+
+
+
Analytics & Reports
+
+
+
Trend Analysis
+
+
+
+
Distribution
+
+
+
+
+
+
+
+ ๐ Coming Soon: AI-Powered Analytics
+
+
+ Advanced predictive analytics, ML-driven insights, and automated recommendations
+ will be available in future updates.
+
+
+
+
+{% endblock %}
+
+{% block app_scripts %}
+
+{% endblock %}
\ No newline at end of file
diff --git a/src/ui/templates/apps/banko.html b/src/ui/templates/apps/banko.html
index 4de62218b908bc70c9f628759e5afa42ab1ed80a..fc54676989f7ae602163ddbeea9296f31d0e1703 100644
--- a/src/ui/templates/apps/banko.html
+++ b/src/ui/templates/apps/banko.html
@@ -1,77 +1,79 @@
-{%extends "shared/app_base.html" %}
+{% extends "shared/app_base.html" %}
-{%block title %}Banko - Financial Management Platform{%endblock %}
+{% block title %}Banko - Financial Management Platform{% endblock %}
-{%set app_config = {
- 'slug': 'banko',
- 'name': 'Banko',
- 'description': 'Financial Management Platform',
- 'entity_name': 'Transaction',
- 'icon': '๐ฐ',
- 'gradient_from': '#ff9a9e',
- 'gradient_to': '#fecfef'
+{% set app_config = {
+'slug': 'banko',
+'name': 'Banko',
+'description': 'Financial Management Platform',
+'entity_name': 'Transaction',
+'icon': '๐ฐ',
+'gradient_from': '#ff9a9e',
+'gradient_to': '#fecfef'
} %}
-{%set app_tabs = [
- {{ 'id': 'dashboard', 'label': 'Dashboard', 'icon': 'tachometer-alt' }},
- {{ 'id': 'transactions', 'label': 'Transactions', 'icon': 'money-bill-wave' }},
- {{ 'id': 'invoices', 'label': 'Invoices', 'icon': 'file-invoice' }},
- {{ 'id': 'reports', 'label': 'Reports', 'icon': 'file-alt' }},
+{% set app_tabs = [
+{'id': 'dashboard', 'label': 'Dashboard', 'icon': 'tachometer-alt'},
+{'id': 'transactions', 'label': 'Transactions', 'icon': 'money-bill-wave'},
+{'id': 'invoices', 'label': 'Invoices', 'icon': 'file-invoice'},
+{'id': 'reports', 'label': 'Reports', 'icon': 'file-alt'}
+] %}{% set stats = [
+{
+'icon': 'list',
+'value': '{{ total_count or 0 }}',
+'label': 'Total Transactions',
+'color': '#ff9a9e',
+'trend': '{{ trend or 0 }}',
+'trend_text': '{{ trend_text or "This month" }}'
+},
+{
+'icon': 'clock',
+'value': '{{ active_count or 0 }}',
+'label': 'Active Today',
+'color': '#10b981',
+'trend': '{{ active_trend or 0 }}',
+'trend_text': '{{ active_trend_text or "24h" }}'
+},
+{
+'icon': 'check-circle',
+'value': '{{ completed_count or 0 }}',
+'label': 'Completed',
+'color': '#3b82f6',
+'trend': '{{ completed_trend or 0 }}',
+'trend_text': '{{ completed_trend_text or "This week" }}'
+},
+{
+'icon': 'chart-line',
+'value': '{{ success_rate or "0" }}%',
+'label': 'Success Rate',
+'color': '#f59e0b',
+'trend': '{{ rate_trend or 0 }}',
+'trend_text': '{{ rate_trend_text or "Overall" }}'
+}
] %}
-{%set stats = [
- {
- 'icon': 'list',
- 'value': '{{ total_count or 0 }}',
- 'label': 'Total Transactions',
- 'color': '#ff9a9e',
- 'trend': '{{ trend or 0 }}',
- 'trend_text': '{{ trend_text or "This month" }}'
- },
- {
- 'icon': 'clock',
- 'value': '{{ active_count or 0 }}',
- 'label': 'Active Today',
- 'color': '#10b981',
- 'trend': '{{ active_trend or 0 }}',
- 'trend_text': '{{ active_trend_text or "24h" }}'
- },
- {
- 'icon': 'check-circle',
- 'value': '{{ completed_count or 0 }}',
- 'label': 'Completed',
- 'color': '#3b82f6',
- 'trend': '{{ completed_trend or 0 }}',
- 'trend_text': '{{ completed_trend_text or "This week" }}'
- },
- {
- 'icon': 'chart-line',
- 'value': '{{ success_rate or "0" }}%',
- 'label': 'Success Rate',
- 'color': '#f59e0b',
- 'trend': '{{ rate_trend or 0 }}',
- 'trend_text': '{{ rate_trend_text or "Overall" }}'
- }
-] %}
-
-{%block dashboard_content %}
+{% block dashboard_content %}
Quick Actions
-