""" YAZ Care Platform - Tool Registry Models v6.0.0 Domain-agnostic tool registration system. Architecture: - Tool = User-created branded product (Surgio, SurgeryPro, ClinicaPlus, etc.) - Domain = Problem space the tool solves (surgical, clinical, laboratory) - Templates = Reusable components within tools (checklists, protocols, workflows) - Installation = Tenant-specific tool activation Philosophy: - Platform is domain-agnostic infrastructure - Tools are domain-specific products built BY users, FOR users - Any user can manufacture/commercialize their tools - Tools compete in marketplace on quality/features/price """ from datetime import datetime, timezone from typing import Optional, List, Dict, Any from uuid import UUID, uuid4 from enum import Enum from decimal import Decimal from pydantic import BaseModel, Field as PydanticField, ConfigDict from sqlmodel import SQLModel, Field, Column, JSON, Relationship # ============================================================================ # ENUMERATIONS # ============================================================================ class ToolDomain(str, Enum): """ Problem domains that tools can address. Domain-agnostic: The platform doesn't care which domain, but tools specialize in solving cases within a domain. """ # Healthcare SURGICAL = "surgical" # Operating rooms, procedures CLINICAL = "clinical" # General patient care LABORATORY = "laboratory" # Lab tests, specimens PHARMACY = "pharmacy" # Medications, dispensing RADIOLOGY = "radiology" # Imaging, diagnostics EMERGENCY = "emergency" # ER, urgent care ICU = "icu" # Intensive care OUTPATIENT = "outpatient" # Clinics, appointments # Support Services HOSPITAL_OPS = "hospital_ops" # Bed management, admissions LOGISTICS = "logistics" # Supply chain, transport INVENTORY = "inventory" # Stock management FINANCE = "finance" # Billing, revenue INSURANCE = "insurance" # Claims, authorizations # Education & Training EDUCATION = "education" # Medical education TRAINING = "training" # Staff competencies RESEARCH = "research" # Clinical research # Field Operations FIELD_OPS = "field_ops" # Community health ACCOMMODATION = "accommodation" # Patient housing MANUFACTURING = "manufacturing" # Device/drug production # Meta GENERAL = "general" # Cross-domain tools CUSTOM = "custom" # User-defined domain class ToolType(str, Enum): """Types of tools users can create""" CASE_MANAGER = "case_manager" # Full case lifecycle management WORKFLOW = "workflow" # Multi-step process automation CALCULATOR = "calculator" # Clinical calculations, scoring MONITOR = "monitor" # Real-time surveillance CHECKLIST = "checklist" # Structured task verification PROTOCOL = "protocol" # Treatment pathways JOURNAL = "journal" # Documentation system DASHBOARD = "dashboard" # Analytics & visualization INTEGRATION = "integration" # External system connectors COMPOSITE = "composite" # Combines multiple types class ToolStatus(str, Enum): """Tool lifecycle status""" DRAFT = "draft" # In development PRIVATE = "private" # Active but not published PENDING_REVIEW = "pending_review" # Awaiting marketplace approval PUBLISHED = "published" # Available in marketplace DEPRECATED = "deprecated" # No longer maintained SUSPENDED = "suspended" # Temporarily disabled class ToolLicense(str, Enum): """Tool licensing models""" PRIVATE = "private" # Owner use only FREE = "free" # Free for all users FREEMIUM = "freemium" # Free basic, paid features SUBSCRIPTION = "subscription" # Monthly/yearly fee PER_USE = "per_use" # Pay per case/usage ENTERPRISE = "enterprise" # Custom enterprise licensing OPEN_SOURCE = "open_source" # Open source (CC/MIT/GPL) # ============================================================================ # DATABASE MODELS # ============================================================================ class Tool(SQLModel, table=True): """ User-created branded tool for case management. This is the core entity that represents a user's product. Tools are manufactured BY users to solve cases in specific domains. Examples: - "Surgio" by User A (surgical domain, case_manager type) - "LabFlow" by User B (laboratory domain, workflow type) - "SepsisAlert" by User C (clinical domain, monitor type) Architecture: - Tool = Product (brand, identity, business model) - Domain = What problems it solves - Type = How it solves them - Templates = Reusable components (checklists, protocols) """ __tablename__ = "tools" __table_args__ = {"schema": "platform", "extend_existing": True} # Identity id: UUID = Field(default_factory=uuid4, primary_key=True) owner_id: UUID = Field(index=True, description="User who created the tool") owner_tenant_id: UUID = Field(index=True, description="Owner's tenant") # Branding (user's product identity) slug: str = Field(max_length=100, index=True, unique=True) name: str = Field(max_length=200, description="Display name (e.g., 'Surgio')") tagline: Optional[str] = Field(default=None, max_length=300) description: str = Field(default="", max_length=5000) icon: Optional[str] = Field(default=None, max_length=100) # Icon name or emoji logo_url: Optional[str] = Field(default=None, max_length=500) primary_color: str = Field(default="#5c6bc0", max_length=20) # Classification domain: ToolDomain = Field(index=True) tool_type: ToolType = Field(index=True) status: ToolStatus = Field(default=ToolStatus.DRAFT, index=True) # Capabilities (what Four Pillars services it uses) uses_checklist: bool = Field(default=False) uses_journal: bool = Field(default=False) uses_monitor: bool = Field(default=False) uses_protocol: bool = Field(default=False) uses_mesh: bool = Field(default=False) # Configuration (JSON - tool-specific settings) config: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) # Templates bundled with tool templates: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) # Standards compliance clinical_standards: List[str] = Field(default_factory=list, sa_column=Column(JSON)) certifications: List[str] = Field(default_factory=list, sa_column=Column(JSON)) # Business Model license: ToolLicense = Field(default=ToolLicense.PRIVATE) price_monthly: Optional[Decimal] = Field(default=None) price_yearly: Optional[Decimal] = Field(default=None) price_per_use: Optional[Decimal] = Field(default=None) trial_days: int = Field(default=0) # Marketplace is_published: bool = Field(default=False, index=True) is_featured: bool = Field(default=False) is_verified: bool = Field(default=False) # Platform verified is_certified: bool = Field(default=False) # Clinical validation # Metrics installation_count: int = Field(default=0) active_users: int = Field(default=0) case_count: int = Field(default=0) rating_average: Decimal = Field(default=Decimal("0.0")) rating_count: int = Field(default=0) # Revenue revenue_total: Decimal = Field(default=Decimal("0.0")) owner_earnings: Decimal = Field(default=Decimal("0.0")) platform_fee_percent: Decimal = Field(default=Decimal("20.0")) # 20% platform fee # Versioning current_version: str = Field(default="1.0.0", max_length=20) # Timestamps created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) published_at: Optional[datetime] = Field(default=None) def to_dict(self) -> Dict[str, Any]: return { "id": str(self.id), "slug": self.slug, "name": self.name, "tagline": self.tagline, "description": self.description, "icon": self.icon, "domain": self.domain.value, "tool_type": self.tool_type.value, "status": self.status.value, "license": self.license.value, "is_published": self.is_published, "installation_count": self.installation_count, "rating_average": float(self.rating_average), } def to_dict_full(self) -> Dict[str, Any]: """Full details for owner/admin""" data = self.to_dict() data.update( { "owner_id": str(self.owner_id), "uses_checklist": self.uses_checklist, "uses_journal": self.uses_journal, "uses_monitor": self.uses_monitor, "uses_protocol": self.uses_protocol, "uses_mesh": self.uses_mesh, "config": self.config, "templates": self.templates, "price_monthly": float(self.price_monthly) if self.price_monthly else None, "revenue_total": float(self.revenue_total), } ) return data class ToolVersion(SQLModel, table=True): """ Version history for tools. Tracks changes and enables rollback. """ __tablename__ = "tool_versions" __table_args__ = {"schema": "platform", "extend_existing": True} id: UUID = Field(default_factory=uuid4, primary_key=True) tool_id: UUID = Field(index=True) version: str = Field(max_length=20) changelog: str = Field(default="", max_length=5000) # Snapshot of tool config at this version config_snapshot: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) templates_snapshot: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) # Release info is_stable: bool = Field(default=True) is_breaking: bool = Field(default=False) released_by: UUID = Field() released_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) class ToolInstallation(SQLModel, table=True): """ Tool installation per tenant. When a tenant "installs" a tool, they can use it to manage cases. This enables the marketplace model where tools are shared/sold. """ __tablename__ = "tool_installations" __table_args__ = {"schema": "platform", "extend_existing": True} id: UUID = Field(default_factory=uuid4, primary_key=True) tool_id: UUID = Field(index=True) tenant_id: UUID = Field(index=True) # Installation details installed_version: str = Field(max_length=20) status: str = Field(default="active", max_length=50) # active, suspended, expired # Customization (tenant-specific overrides) custom_config: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) custom_branding: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) # License license_type: str = Field(max_length=50) license_expires_at: Optional[datetime] = Field(default=None) is_trial: bool = Field(default=False) trial_expires_at: Optional[datetime] = Field(default=None) # Usage tracking case_count: int = Field(default=0) user_count: int = Field(default=0) last_used_at: Optional[datetime] = Field(default=None) # Billing billing_cycle: Optional[str] = Field(default=None) # monthly, yearly next_billing_at: Optional[datetime] = Field(default=None) amount_paid: Decimal = Field(default=Decimal("0.0")) # Timestamps installed_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) # ============================================================================ # PYDANTIC SCHEMAS # ============================================================================ class ToolCreate(BaseModel): """Create a new tool""" slug: str = PydanticField(..., min_length=3, max_length=100) name: str = PydanticField(..., min_length=1, max_length=200) tagline: Optional[str] = PydanticField(None, max_length=300) description: str = PydanticField("", max_length=5000) icon: Optional[str] = PydanticField(None, max_length=100) primary_color: str = PydanticField("#5c6bc0", max_length=20) domain: ToolDomain tool_type: ToolType uses_checklist: bool = False uses_journal: bool = False uses_monitor: bool = False uses_protocol: bool = False uses_mesh: bool = False config: Dict[str, Any] = {} templates: Dict[str, Any] = {} clinical_standards: List[str] = [] license: ToolLicense = ToolLicense.PRIVATE model_config = ConfigDict( json_schema_extra={ "examples": [ { "slug": "my-surgery-tool", "name": "MySurgeryTool", "tagline": "Efficient surgical case management", "domain": "surgical", "tool_type": "case_manager", "uses_checklist": True, "uses_journal": True, "uses_protocol": True, } ] } ) class ToolUpdate(BaseModel): """Update an existing tool""" name: Optional[str] = None tagline: Optional[str] = None description: Optional[str] = None icon: Optional[str] = None primary_color: Optional[str] = None uses_checklist: Optional[bool] = None uses_journal: Optional[bool] = None uses_monitor: Optional[bool] = None uses_protocol: Optional[bool] = None uses_mesh: Optional[bool] = None config: Optional[Dict[str, Any]] = None templates: Optional[Dict[str, Any]] = None clinical_standards: Optional[List[str]] = None license: Optional[ToolLicense] = None price_monthly: Optional[Decimal] = None price_yearly: Optional[Decimal] = None class ToolResponse(BaseModel): """Tool response for API""" id: UUID slug: str name: str tagline: Optional[str] description: str icon: Optional[str] primary_color: str domain: ToolDomain tool_type: ToolType status: ToolStatus uses_checklist: bool uses_journal: bool uses_monitor: bool uses_protocol: bool uses_mesh: bool is_published: bool is_verified: bool installation_count: int rating_average: float rating_count: int created_at: datetime model_config = ConfigDict(from_attributes=True) class ToolInstallRequest(BaseModel): """Request to install a tool""" tool_id: UUID license_type: str = "free" custom_config: Dict[str, Any] = {} class ToolInstallResponse(BaseModel): """Installation confirmation""" installation_id: UUID tool_id: UUID tool_name: str tenant_id: UUID installed_version: str status: str installed_at: datetime # ============================================================================= # LAYER 1 — YAZ Platform: ActivatedTool # ============================================================================= class ActivatedTool(SQLModel, table=True): """ Per-case tool activation record — tracks which tools have been activated for a specific case by a tenant. While ToolInstallation tracks tenant-level tool subscriptions, ActivatedTool tracks per-case activations: which tools are live for this specific case, when they were activated, and by whom. Use-cases: - Surgio activates "WHO Checklist" tool when a bloc case enters GO state. - Azul activates "CNSS Billing" tool when a pathway is confirmed public. - Any engine activates domain-specific intelligence modules per case. Security: tenant_id mandatory; case_ref anonymized Performance: <200ms; indexed on case_id + tenant_id """ __tablename__ = "activated_tools" __table_args__ = ({"extend_existing": True},) id: UUID = Field(default_factory=uuid4, primary_key=True) tenant_id: UUID = Field(nullable=False, index=True) # What case this activation belongs to case_id: Optional[UUID] = Field( default=None, index=True, description="Platform case ID (Trace ID from the Traces engine)", ) case_ref: Optional[str] = Field( default=None, max_length=50, index=True, description="Anonymized case reference (e.g. SRG-2026-001234)", ) engine: Optional[str] = Field( default=None, max_length=50, index=True, description="Engine that owns this case: surgio | clinica | azul | etc.", ) # Tool identity tool_id: Optional[UUID] = Field( default=None, index=True, description="FK to tools.id (if tool is registered in the tool registry)", ) tool_slug: str = Field( max_length=100, index=True, description="Slug of the activated tool (e.g. 'who_checklist', 'cnss_billing')", ) tool_version: Optional[str] = Field(default=None, max_length=20) # Activation metadata activated_by: Optional[UUID] = Field( default=None, description="User ID of the actor who triggered activation", ) activated_at: datetime = Field( default_factory=lambda: datetime.now(timezone.utc), index=True, ) activation_trigger: Optional[str] = Field( default=None, max_length=100, description="Event or action that triggered activation: go_decision | case_scheduled | manual | etc.", ) # Configuration snapshot at time of activation configuration: Optional[Dict[str, Any]] = Field( default=None, sa_column=Column(JSON), description="Tool configuration applied for this specific case activation", ) # Lifecycle is_active: bool = Field(default=True, index=True) deactivated_at: Optional[datetime] = Field(default=None) deactivated_by: Optional[UUID] = Field(default=None) deactivation_reason: Optional[str] = Field(default=None, max_length=200) # Timestamps created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) updated_at: Optional[datetime] = Field(default=None) # Export __all__ = [ # Enums "ToolDomain", "ToolType", "ToolStatus", "ToolLicense", # Models "Tool", "ToolVersion", "ToolInstallation", "ActivatedTool", # Schemas "ToolCreate", "ToolUpdate", "ToolResponse", "ToolInstallRequest", "ToolInstallResponse", ]