Download src/core/database/tools.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/database/tools.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/database/tools.py
-
curl -L -o tools.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/database/tools.py
13.1 kB
| """ | |
| Tool Models for YAZ Care Platform | |
| Sprint 34 Phase 2: Application/Tool Registry | |
| Implements the tool registry that maps software applications to systems. | |
| Tools are the actual software products (Surgio, Clinica, Banko, etc.) that | |
| can be enabled/disabled per system. | |
| Architecture: | |
| Tool (slug='surgio', module_path='apps.surgio') | |
| ↓ enabled via | |
| SystemTool (links System to Tool with config) | |
| ↓ available to | |
| Tenant (can use enabled tools) | |
| Security: | |
| - Tool enablement changes are audit-logged | |
| - Module paths are validated (prevent code injection) | |
| - Only ADMIN/SYSTEM_MANAGER can modify tool registry | |
| Standards: Multi-tenant safe, RBAC enforced, audit-logged | |
| """ | |
| from __future__ import annotations | |
| import uuid | |
| from datetime import datetime, timezone | |
| from typing import Optional, Dict, Any | |
| from sqlmodel import SQLModel, Field, Relationship, Column, JSON | |
| from sqlalchemy import String, Text, Boolean, UniqueConstraint | |
| from sqlalchemy.dialects.postgresql import UUID | |
| # Import schema helper from governance | |
| from core.database.governance import _get_table_args | |
| # ============================================================================ | |
| # BASE MIXINS | |
| # ============================================================================ | |
| class TimestampMixin(SQLModel): | |
| """Timestamp tracking""" | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False) | |
| updated_at: Optional[datetime] = Field( | |
| default_factory=lambda: datetime.now(timezone.utc), | |
| nullable=True, | |
| sa_column_kwargs={"onupdate": lambda: datetime.now(timezone.utc)} | |
| ) | |
| class UUIDMixin(SQLModel): | |
| """UUID primary key""" | |
| id: uuid.UUID = Field( | |
| default_factory=uuid.uuid4, | |
| sa_column=Column(UUID(as_uuid=True), primary_key=True, nullable=False) | |
| ) | |
| # ============================================================================ | |
| # TOOL MODEL | |
| # ============================================================================ | |
| class Tool(TimestampMixin, table=True): | |
| """ | |
| Tool - Software application/product registry | |
| Represents individual software applications (Surgio, Clinica, Banko, etc.) | |
| that can be installed and enabled across different systems. | |
| Key Concept: Tools are PRODUCT SURFACE - these names belong in code! | |
| ✅ Correct: apps/surgio/, /api/surgio/, from apps.surgio import router | |
| ❌ Wrong: Use legal entity or system names in code structure | |
| Security: | |
| - module_path must be validated before import (prevent injection) | |
| - Only whitelisted paths allowed: ^apps\\.[a-z]+$ | |
| - Tool registry changes are audit-logged | |
| Examples: | |
| - Surgio: Surgical management (ASA/WHO compliance) | |
| - Clinica: Clinical data & decision support | |
| - Banko: Financial management & billing | |
| """ | |
| __tablename__ = "tools" | |
| __table_args__ = _get_table_args('governance') | |
| # Primary key | |
| id: uuid.UUID = Field( | |
| default_factory=uuid.uuid4, | |
| sa_column=Column(UUID(as_uuid=True), primary_key=True, nullable=False) | |
| ) | |
| # Identification | |
| slug: str = Field( | |
| max_length=50, | |
| nullable=False, | |
| unique=True, | |
| index=True, | |
| description="URL-safe identifier (e.g., 'surgio', 'clinica', 'banko')" | |
| ) | |
| display_name: str = Field( | |
| max_length=255, | |
| nullable=False, | |
| description="Human-readable name (e.g., 'Surgio (Surgical Management)')" | |
| ) | |
| # Code integration | |
| module_path: str = Field( | |
| max_length=255, | |
| nullable=False, | |
| description="Python module path (e.g., 'apps.surgio', 'apps.clinica')" | |
| ) | |
| # Metadata | |
| description: Optional[str] = Field( | |
| default=None, | |
| sa_column=Column(Text), | |
| description="Tool capabilities and purpose" | |
| ) | |
| version: str = Field( | |
| default="1.0.0", | |
| max_length=20, | |
| description="Current tool version (semantic versioning)" | |
| ) | |
| # Documentation | |
| documentation_url: Optional[str] = Field( | |
| default=None, | |
| max_length=500, | |
| description="Link to tool documentation" | |
| ) | |
| icon_url: Optional[str] = Field( | |
| default=None, | |
| max_length=500, | |
| description="Tool icon/logo URL" | |
| ) | |
| # Categories (for UI organization) | |
| category: Optional[str] = Field( | |
| default="general", | |
| max_length=50, | |
| description="Tool category (clinical, financial, logistics, etc.)" | |
| ) | |
| tags: Optional[Dict[str, Any]] = Field( | |
| default=None, | |
| sa_column=Column(JSON), | |
| description="Searchable tags: ['healthcare', 'surgery', 'compliance']" | |
| ) | |
| # Requirements | |
| requires_hipaa_compliance: bool = Field( | |
| default=True, | |
| nullable=False, | |
| description="Whether tool handles PHI (most healthcare tools do)" | |
| ) | |
| min_subscription_tier: Optional[str] = Field( | |
| default="basic", | |
| max_length=50, | |
| description="Minimum subscription tier required (basic, professional, enterprise)" | |
| ) | |
| # Status | |
| is_active: bool = Field( | |
| default=True, | |
| nullable=False, | |
| description="Whether tool is available for installation" | |
| ) | |
| is_beta: bool = Field( | |
| default=False, | |
| nullable=False, | |
| description="Whether tool is in beta (show warning in UI)" | |
| ) | |
| # Relationships (will be added in respective modules) | |
| # system_tools: List["SystemTool"] = Relationship(back_populates="tool") | |
| class Config: | |
| """Pydantic configuration""" | |
| json_schema_extra = { | |
| "example": { | |
| "slug": "surgio", | |
| "display_name": "Surgio (Surgical Management)", | |
| "module_path": "apps.surgio", | |
| "description": "Comprehensive surgical case management with ASA risk assessment and WHO checklist compliance", | |
| "version": "5.0.2", | |
| "category": "clinical", | |
| "tags": ["surgery", "perioperative", "compliance", "ASA", "WHO"], | |
| "requires_hipaa_compliance": True, | |
| "min_subscription_tier": "professional", | |
| "is_active": True, | |
| "is_beta": False | |
| } | |
| } | |
| def __repr__(self) -> str: | |
| """String representation""" | |
| return f"<Tool(slug='{self.slug}', version='{self.version}')>" | |
| def to_dict(self) -> Dict[str, Any]: | |
| """Dictionary representation for API responses""" | |
| return { | |
| "id": str(self.id), | |
| "slug": self.slug, | |
| "display_name": self.display_name, | |
| "module_path": self.module_path, | |
| "description": self.description, | |
| "version": self.version, | |
| "documentation_url": self.documentation_url, | |
| "icon_url": self.icon_url, | |
| "category": self.category, | |
| "tags": self.tags, | |
| "requires_hipaa_compliance": self.requires_hipaa_compliance, | |
| "min_subscription_tier": self.min_subscription_tier, | |
| "is_active": self.is_active, | |
| "is_beta": self.is_beta, | |
| "created_at": self.created_at.isoformat() if self.created_at else None, | |
| "updated_at": self.updated_at.isoformat() if self.updated_at else None | |
| } | |
| def validate_module_path(self) -> bool: | |
| """ | |
| Validate module path against whitelist. | |
| Security: Prevents code injection via malicious module paths. | |
| Only allows paths matching: ^apps\\.[a-z]+$ | |
| Returns: | |
| bool: True if valid, False otherwise | |
| """ | |
| import re | |
| pattern = r'^apps\.[a-z]+$' | |
| return bool(re.match(pattern, self.module_path)) | |
| # ============================================================================ | |
| # SYSTEM-TOOL MAPPING MODEL | |
| # ============================================================================ | |
| class SystemTool(TimestampMixin, table=True): | |
| """ | |
| SystemTool - Enables/disables tools per system | |
| Links systems to tools with system-specific configuration. | |
| This allows YAZ to enable all 17 tools while AYRAD only enables | |
| logistics and analytics tools. | |
| Key Features: | |
| - Per-system tool enablement (enable/disable) | |
| - System-specific tool configuration | |
| - Audit trail of tool activation changes | |
| Security: | |
| - Changes are audit-logged (who enabled what, when) | |
| - Only ADMIN/SYSTEM_MANAGER can modify | |
| - Tenant permissions inherit from system tool enablement | |
| Example: | |
| YAZ system enables: surgio, clinica, labo, pharma (all tools) | |
| AYRAD system enables: movio, stoka, campo (logistics only) | |
| """ | |
| __tablename__ = "system_tools" | |
| __table_args__ = ( | |
| UniqueConstraint('system_id', 'tool_id', name='uq_system_tool'), | |
| _get_table_args('governance') | |
| ) | |
| # Primary key | |
| id: uuid.UUID = Field( | |
| default_factory=uuid.uuid4, | |
| sa_column=Column(UUID(as_uuid=True), primary_key=True, nullable=False) | |
| ) | |
| # Foreign keys | |
| system_id: uuid.UUID = Field( | |
| foreign_key="systems.id", | |
| nullable=False, | |
| index=True, | |
| description="System that has this tool available" | |
| ) | |
| tool_id: uuid.UUID = Field( | |
| foreign_key="tools.id", | |
| nullable=False, | |
| index=True, | |
| description="Tool that is available in this system" | |
| ) | |
| # Enablement | |
| enabled: bool = Field( | |
| default=True, | |
| nullable=False, | |
| description="Whether tool is enabled for this system" | |
| ) | |
| # Configuration | |
| config: Optional[Dict[str, Any]] = Field( | |
| default=None, | |
| sa_column=Column(JSON), | |
| description="System-specific tool configuration overrides" | |
| ) | |
| # Limits (per system) | |
| max_usage_per_tenant: Optional[int] = Field( | |
| default=None, | |
| description="Maximum usage/calls per tenant per month (null = unlimited)" | |
| ) | |
| # Metadata | |
| enabled_at: Optional[datetime] = Field( | |
| default=None, | |
| description="When tool was first enabled for this system" | |
| ) | |
| enabled_by: Optional[uuid.UUID] = Field( | |
| default=None, | |
| sa_column=Column(UUID(as_uuid=True)), | |
| description="User ID who enabled this tool (audit trail)" | |
| ) | |
| disabled_at: Optional[datetime] = Field( | |
| default=None, | |
| description="When tool was disabled (if applicable)" | |
| ) | |
| disabled_by: Optional[uuid.UUID] = Field( | |
| default=None, | |
| sa_column=Column(UUID(as_uuid=True)), | |
| description="User ID who disabled this tool (audit trail)" | |
| ) | |
| # Notes (for audit/documentation) | |
| notes: Optional[str] = Field( | |
| default=None, | |
| sa_column=Column(Text), | |
| description="Reason for enabling/disabling, deployment notes" | |
| ) | |
| # Relationships (will be added in respective modules) | |
| # system: System = Relationship(back_populates="tools") | |
| # tool: Tool = Relationship(back_populates="system_tools") | |
| class Config: | |
| """Pydantic configuration""" | |
| json_schema_extra = { | |
| "example": { | |
| "system_id": "sys-yaz-001", | |
| "tool_id": "tool-surgio", | |
| "enabled": True, | |
| "config": { | |
| "feature_flags": { | |
| "asa_risk_assessment": True, | |
| "who_checklist_v2": True | |
| }, | |
| "limits": { | |
| "max_cases_per_day": 1000 | |
| } | |
| }, | |
| "max_usage_per_tenant": 10000, | |
| "notes": "Enabled for all professional+ tier tenants" | |
| } | |
| } | |
| def __repr__(self) -> str: | |
| """String representation""" | |
| status = "enabled" if self.enabled else "disabled" | |
| return f"<SystemTool(system={self.system_id}, tool={self.tool_id}, {status})>" | |
| def to_dict(self) -> Dict[str, Any]: | |
| """Dictionary representation for API responses""" | |
| return { | |
| "id": str(self.id), | |
| "system_id": str(self.system_id), | |
| "tool_id": str(self.tool_id), | |
| "enabled": self.enabled, | |
| "config": self.config, | |
| "max_usage_per_tenant": self.max_usage_per_tenant, | |
| "enabled_at": self.enabled_at.isoformat() if self.enabled_at else None, | |
| "enabled_by": str(self.enabled_by) if self.enabled_by else None, | |
| "disabled_at": self.disabled_at.isoformat() if self.disabled_at else None, | |
| "disabled_by": str(self.disabled_by) if self.disabled_by else None, | |
| "notes": self.notes, | |
| "created_at": self.created_at.isoformat() if self.created_at else None, | |
| "updated_at": self.updated_at.isoformat() if self.updated_at else None | |
| } | |
| # ============================================================================ | |
| # EXPORT | |
| # ============================================================================ | |
| __all__ = [ | |
| "Tool", | |
| "SystemTool", | |
| ] | |