Spaces:
Paused

File size: 13,095 Bytes
ff28ba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ca1d
ff28ba2
 
 
 
 
 
9ff954c
 
 
ff28ba2
 
 
 
 
 
 
091ca1d
ff28ba2
091ca1d
ff28ba2
091ca1d
ff28ba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ff954c
ff28ba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ff954c
ff28ba2
 
 
 
 
 
 
 
 
 
9ff954c
ff28ba2
 
 
 
 
9ff954c
ff28ba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
"""
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",
]