#!/usr/bin/env python3 """ YAZ Care Platform - UI/UX Generator Generates standardized, homogeneous UI templates for all healthcare apps Usage: python scripts/generators/generate_ui.py --app movio python scripts/generators/generate_ui.py --all Features: - Consistent HTMX + Alpine.js patterns - Responsive mobile-first design - App-specific gradients and branding - Open-source CRUD operations - Export/Import functionality - Search and filtering - Pagination and sorting """ import os import sys from pathlib import Path from typing import Dict, List, Optional import argparse # Add src to path sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) # ============================================================================ # App Configurations # ============================================================================ APP_CONFIGS = { "surgio": { "name": "Surgio", "description": "Advanced Surgical Management", "entity_name": "Surgery Case", "icon": "šŸ”Ŗ", "gradient_from": "#667eea", "gradient_to": "#764ba2", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "cases", "label": "Cases", "icon": "procedures"}, {"id": "schedule", "label": "OR Schedule", "icon": "calendar"}, {"id": "analytics", "label": "Analytics", "icon": "chart-line"}, ], "features": ["crud", "search", "export", "import", "analytics"] }, "clinica": { "name": "Clinica", "description": "Clinical Data Management", "entity_name": "Patient", "icon": "šŸ„", "gradient_from": "#f093fb", "gradient_to": "#f5576c", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "patients", "label": "Patients", "icon": "user-injured"}, {"id": "encounters", "label": "Encounters", "icon": "notes-medical"}, {"id": "vitals", "label": "Vitals", "icon": "heartbeat"}, ], "features": ["crud", "search", "export", "fhir"] }, "labo": { "name": "Labo", "description": "Laboratory Information System", "entity_name": "Test", "icon": "šŸ”¬", "gradient_from": "#43e97b", "gradient_to": "#38f9d7", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "tests", "label": "Tests", "icon": "vial"}, {"id": "results", "label": "Results", "icon": "clipboard-check"}, {"id": "qc", "label": "Quality Control", "icon": "check-circle"}, ], "features": ["crud", "search", "export", "qc_charts"] }, "stay": { "name": "Stay", "description": "Hospital Operations Management", "entity_name": "Admission", "icon": "šŸ„", "gradient_from": "#6a11cb", "gradient_to": "#2575fc", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "beds", "label": "Bed Management", "icon": "bed"}, {"id": "admissions", "label": "Admissions", "icon": "user-plus"}, {"id": "capacity", "label": "Capacity", "icon": "chart-bar"}, ], "features": ["crud", "search", "export", "capacity_planning"] }, "pharma": { "name": "Pharma", "description": "Pharmaceutical Management", "entity_name": "Prescription", "icon": "šŸ’Š", "gradient_from": "#4facfe", "gradient_to": "#00f2fe", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "prescriptions", "label": "Prescriptions", "icon": "prescription"}, {"id": "inventory", "label": "Inventory", "icon": "pills"}, {"id": "interactions", "label": "Interactions", "icon": "exclamation-triangle"}, ], "features": ["crud", "search", "export", "drug_interactions"] }, "educa": { "name": "Educa", "description": "Medical Education & Training", "entity_name": "Course", "icon": "šŸ“š", "gradient_from": "#fa709a", "gradient_to": "#fee140", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "courses", "label": "Courses", "icon": "book"}, {"id": "enrollments", "label": "Enrollments", "icon": "user-graduate"}, {"id": "competencies", "label": "Competencies", "icon": "certificate"}, ], "features": ["crud", "search", "export", "lms"] }, "insura": { "name": "Insura", "description": "Insurance Analytics & Management", "entity_name": "Claim", "icon": "šŸ›”ļø", "gradient_from": "#30cfd0", "gradient_to": "#330867", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "claims", "label": "Claims", "icon": "file-invoice-dollar"}, {"id": "authorizations", "label": "Authorizations", "icon": "check-square"}, {"id": "analytics", "label": "Analytics", "icon": "chart-pie"}, ], "features": ["crud", "search", "export", "risk_analytics"] }, "movio": { "name": "Movio", "description": "Medical Logistics & Inventory", "entity_name": "Item", "icon": "šŸ“¦", "gradient_from": "#a8edea", "gradient_to": "#fed6e3", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "inventory", "label": "Inventory", "icon": "boxes"}, {"id": "orders", "label": "Orders", "icon": "shopping-cart"}, {"id": "vendors", "label": "Vendors", "icon": "truck"}, ], "features": ["crud", "search", "export", "import", "barcode"] }, "stoka": { "name": "Stoka", "description": "Stock Management System", "entity_name": "Stock Item", "icon": "šŸ“Š", "gradient_from": "#f77062", "gradient_to": "#fe5196", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "stock", "label": "Stock", "icon": "warehouse"}, {"id": "movements", "label": "Movements", "icon": "exchange-alt"}, {"id": "counts", "label": "Cycle Counts", "icon": "clipboard-list"}, ], "features": ["crud", "search", "export", "import", "cycle_counts"] }, "campo": { "name": "Campo", "description": "Field Operations Management", "entity_name": "Program", "icon": "šŸš‘", "gradient_from": "#ff6e7f", "gradient_to": "#bfe9ff", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "clinics", "label": "Mobile Clinics", "icon": "ambulance"}, {"id": "programs", "label": "Programs", "icon": "project-diagram"}, {"id": "resources", "label": "Resources", "icon": "toolbox"}, ], "features": ["crud", "search", "export", "gps_tracking"] }, "banko": { "name": "Banko", "description": "Financial Management Platform", "entity_name": "Transaction", "icon": "šŸ’°", "gradient_from": "#ff9a9e", "gradient_to": "#fecfef", "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"}, ], "features": ["crud", "search", "export", "financial_reports"] }, "casa": { "name": "Casa", "description": "Accommodation Management", "entity_name": "Room", "icon": "šŸØ", "gradient_from": "#e0c3fc", "gradient_to": "#8ec5fc", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "rooms", "label": "Rooms", "icon": "door-open"}, {"id": "reservations", "label": "Reservations", "icon": "calendar-check"}, {"id": "guests", "label": "Guests", "icon": "users"}, ], "features": ["crud", "search", "export", "booking"] }, "fabrica": { "name": "Fabrica", "description": "Manufacturing Operations", "entity_name": "Batch", "icon": "šŸ­", "gradient_from": "#ffecd2", "gradient_to": "#fcb69f", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "batches", "label": "Production Batches", "icon": "industry"}, {"id": "quality", "label": "Quality Tests", "icon": "check-double"}, {"id": "ncr", "label": "Non-Conformance", "icon": "exclamation-circle"}, ], "features": ["crud", "search", "export", "quality_control"] }, "trena": { "name": "Trena", "description": "Training Coordination", "entity_name": "Training", "icon": "šŸŽ“", "gradient_from": "#ffecd2", "gradient_to": "#fcb69f", "tabs": [ {"id": "dashboard", "label": "Dashboard", "icon": "tachometer-alt"}, {"id": "courses", "label": "Courses", "icon": "book-open"}, {"id": "enrollments", "label": "Enrollments", "icon": "user-check"}, {"id": "certifications", "label": "Certifications", "icon": "award"}, ], "features": ["crud", "search", "export", "compliance_tracking"] } } # ============================================================================ # Template Generators # ============================================================================ def generate_app_template(app_slug: str, config: Dict) -> str: """Generate main app template HTML""" tabs_html = "" for tab in config["tabs"]: tabs_html += f""" {{{{ 'id': '{tab["id"]}', 'label': '{tab["label"]}', 'icon': '{tab["icon"]}' }}}},""" return f"""{{%extends "shared/app_base.html" %}} {{%block title %}}{config['name']} - {config['description']}{{%endblock %}} {{%set app_config = {{ 'slug': '{app_slug}', 'name': '{config['name']}', 'description': '{config['description']}', 'entity_name': '{config['entity_name']}', 'icon': '{config['icon']}', 'gradient_from': '{config['gradient_from']}', 'gradient_to': '{config['gradient_to']}' }} %}} {{%set app_tabs = [{tabs_html} ] %}} {{%set stats = [ {{ 'icon': 'list', 'value': '{{{{ total_count or 0 }}}}', 'label': 'Total {config['entity_name']}s', 'color': '{config['gradient_from']}', '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 %}}

Quick Actions

Loading {config['entity_name'].lower()}s...

{{%endblock %}} {{%block additional_tabs %}}

All {config['entity_name']}s

Loading...

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 %}} """ def generate_routes_boilerplate(app_slug: str, config: Dict) -> str: """Generate routes boilerplate for open-source features""" return f'''""" {config['name']} - 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 ( {config['entity_name'].replace(' ', '')}Create, {config['entity_name'].replace(' ', '')}Update, {config['entity_name'].replace(' ', '')}Response, {config['entity_name'].replace(' ', '')}List ) from .service import {config['name']}Service router = APIRouter(prefix="/apps/{app_slug}", tags=["{config['name']}"]) # ============================================================================ # UI Routes (HTML responses) # ============================================================================ @router.get("/", response_class=HTMLResponse) async def dashboard( tenant_id: str = Depends(verify_tenant_access), service: {config['name']}Service = 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/{app_slug}_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: {config['name']}Service = 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={config['entity_name'].replace(' ', '')}Response, status_code=201) async def create_item( data: {config['entity_name'].replace(' ', '')}Create, current_user = Depends(get_current_user), tenant_id: str = Depends(verify_tenant_access), service: {config['name']}Service = Depends() ): """ Create new {config['entity_name'].lower()} Clinical Context: {config['description']} Performance: <200ms target """ return await service.create(data, tenant_id, current_user.id) @router.get("/items", response_model={config['entity_name'].replace(' ', '')}List) 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: {config['name']}Service = Depends() ): """ List {config['entity_name'].lower()}s 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={config['entity_name'].replace(' ', '')}Response) async def get_item( item_id: UUID, tenant_id: str = Depends(verify_tenant_access), service: {config['name']}Service = Depends() ): """Get {config['entity_name'].lower()} by ID""" item = await service.get(item_id, tenant_id) if not item: raise HTTPException(status_code=404, detail="{config['entity_name']} not found") return item @router.patch("/items/{{item_id}}", response_model={config['entity_name'].replace(' ', '')}Response) async def update_item( item_id: UUID, data: {config['entity_name'].replace(' ', '')}Update, current_user = Depends(get_current_user), tenant_id: str = Depends(verify_tenant_access), service: {config['name']}Service = Depends() ): """Update {config['entity_name'].lower()}""" item = await service.update(item_id, data, tenant_id, current_user.id) if not item: raise HTTPException(status_code=404, detail="{config['entity_name']} 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: {config['name']}Service = Depends() ): """Soft delete {config['entity_name'].lower()}""" success = await service.delete(item_id, tenant_id, current_user.id) if not success: raise HTTPException(status_code=404, detail="{config['entity_name']} not found") # ============================================================================ # Export Routes (Open Source) # ============================================================================ @router.get("/export") async def export_items( format: str = Query("csv", pattern="^(csv|xlsx|pdf)$"), tenant_id: str = Depends(verify_tenant_access), service: {config['name']}Service = Depends() ): """ Export {config['entity_name'].lower()}s 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={app_slug}_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: {config['name']}Service = Depends() ): """ Bulk import {config['entity_name'].lower()}s 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" ] }} ''' def generate_all_apps(): """Generate UI templates and route boilerplate for all apps""" base_path = Path(__file__).parent.parent.parent templates_dir = base_path / "src" / "ui" / "templates" / "apps" routes_dir = base_path / "src" / "apps" templates_dir.mkdir(parents=True, exist_ok=True) print("šŸŽØ Generating UI templates and routes for all apps...\n") for app_slug, config in APP_CONFIGS.items(): print(f"✨ Generating {config['name']} ({app_slug})...") # Generate template template_content = generate_app_template(app_slug, config) template_path = templates_dir / f"{app_slug}_new.html" with open(template_path, "w") as f: f.write(template_content) print(f" āœ… Template: {template_path}") # Generate routes boilerplate (as documentation) routes_content = generate_routes_boilerplate(app_slug, config) routes_doc_path = routes_dir / app_slug / "ROUTES_BOILERPLATE.py" if not routes_doc_path.parent.exists(): routes_doc_path.parent.mkdir(parents=True, exist_ok=True) with open(routes_doc_path, "w") as f: f.write(routes_content) print(f" āœ… Routes boilerplate: {routes_doc_path}") print() print("✨ All templates and boilerplate generated successfully!") print(f"\nšŸ“ Templates location: {templates_dir}") print(f"šŸ“ Routes boilerplate: {routes_dir}/{{app}}/ROUTES_BOILERPLATE.py") def main(): parser = argparse.ArgumentParser(description="Generate UI/UX templates for YAZ Care apps") parser.add_argument("--app", help="Generate for specific app (e.g., movio)") parser.add_argument("--all", action="store_true", help="Generate for all apps") args = parser.parse_args() if args.all: generate_all_apps() elif args.app: if args.app in APP_CONFIGS: config = APP_CONFIGS[args.app] # Generate single app print(f"Generating {config['name']}...") # Implementation here else: print(f"āŒ Unknown app: {args.app}") print(f"Available apps: {', '.join(APP_CONFIGS.keys())}") else: parser.print_help() if __name__ == "__main__": main()