Download scripts/generators/generate_ui.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 30 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/generators/generate_ui.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/scripts/generators/generate_ui.py
-
curl -L -o generate_ui.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/generators/generate_ui.py
30 kB
| #!/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 --> | |
| <div class="bg-white rounded-lg shadow-sm p-6 mb-6"> | |
| <h2 class="text-lg font-semibold text-gray-900 mb-4">Quick Actions</h2> | |
| <div class="grid grid-cols-2 md:grid-cols-4 gap-4"> | |
| <button onclick="showNewModal()" class="flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-[{config['gradient_from']}] to-[{config['gradient_to']}] text-white rounded-lg hover:shadow-lg transition-shadow"> | |
| <i class="fas fa-plus"></i> | |
| <span>New {config['entity_name']}</span> | |
| </button> | |
| <button onclick="showImportModal()" class="flex items-center justify-center gap-2 px-4 py-3 bg-white border-2 border-gray-200 text-gray-700 rounded-lg hover:border-gray-300 transition-colors"> | |
| <i class="fas fa-file-import"></i> | |
| <span>Import</span> | |
| </button> | |
| <button onclick="exportData()" class="flex items-center justify-center gap-2 px-4 py-3 bg-white border-2 border-gray-200 text-gray-700 rounded-lg hover:border-gray-300 transition-colors"> | |
| <i class="fas fa-file-export"></i> | |
| <span>Export</span> | |
| </button> | |
| <button onclick="refreshData()" class="flex items-center justify-center gap-2 px-4 py-3 bg-white border-2 border-gray-200 text-gray-700 rounded-lg hover:border-gray-300 transition-colors"> | |
| <i class="fas fa-sync-alt"></i> | |
| <span>Refresh</span> | |
| </button> | |
| </div> | |
| </div> | |
| <!-- Search and Filter --> | |
| <div class="bg-white rounded-lg shadow-sm p-6 mb-6"> | |
| <div class="flex flex-col md:flex-row gap-4"> | |
| <div class="flex-1"> | |
| <div class="relative"> | |
| <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i> | |
| <input | |
| type="text" | |
| id="search-input" | |
| placeholder="Search {config['entity_name'].lower()}s..." | |
| class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[{config['gradient_from']}] focus:border-transparent" | |
| hx-get="/apps/{app_slug}/search" | |
| hx-trigger="keyup changed delay:300ms" | |
| hx-target="#data-table" | |
| hx-include="[name='status'], [name='sort']" | |
| > | |
| </div> | |
| </div> | |
| <div class="flex gap-2"> | |
| <select name="status" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[{config['gradient_from']}] focus:border-transparent" | |
| hx-get="/apps/{app_slug}/search" | |
| hx-trigger="change" | |
| hx-target="#data-table" | |
| hx-include="[name='search'], [name='sort']"> | |
| <option value="">All Status</option> | |
| <option value="active">Active</option> | |
| <option value="pending">Pending</option> | |
| <option value="completed">Completed</option> | |
| <option value="cancelled">Cancelled</option> | |
| </select> | |
| <select name="sort" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[{config['gradient_from']}] focus:border-transparent" | |
| hx-get="/apps/{app_slug}/search" | |
| hx-trigger="change" | |
| hx-target="#data-table" | |
| hx-include="[name='search'], [name='status']"> | |
| <option value="-created_at">Newest First</option> | |
| <option value="created_at">Oldest First</option> | |
| <option value="name">Name A-Z</option> | |
| <option value="-name">Name Z-A</option> | |
| </select> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Data Table --> | |
| <div class="bg-white rounded-lg shadow-sm overflow-hidden"> | |
| <div id="data-table" | |
| hx-get="/apps/{app_slug}/table" | |
| hx-trigger="load" | |
| hx-swap="innerHTML"> | |
| <!-- Loading state --> | |
| <div class="p-12 text-center"> | |
| <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-[{config['gradient_from']}]"></div> | |
| <p class="mt-4 text-gray-500">Loading {config['entity_name'].lower()}s...</p> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Pagination will be included in table response --> | |
| {{%endblock %}} | |
| {{%block additional_tabs %}} | |
| <!-- Cases Tab --> | |
| <div id="cases-tab" class="app-tab-content"> | |
| <div class="p-6"> | |
| <h2 class="text-xl font-semibold mb-4">All {config['entity_name']}s</h2> | |
| <div id="cases-list" | |
| hx-get="/apps/{app_slug}/cases" | |
| hx-trigger="load" | |
| hx-swap="innerHTML"> | |
| Loading... | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Analytics Tab --> | |
| <div id="analytics-tab" class="app-tab-content"> | |
| <div class="p-6"> | |
| <h2 class="text-xl font-semibold mb-4">Analytics & Reports</h2> | |
| <div class="grid grid-cols-1 md:grid-cols-2 gap-6"> | |
| <div class="bg-white p-6 rounded-lg shadow-sm"> | |
| <h3 class="font-medium mb-4">Trend Analysis</h3> | |
| <canvas id="trend-chart"></canvas> | |
| </div> | |
| <div class="bg-white p-6 rounded-lg shadow-sm"> | |
| <h3 class="font-medium mb-4">Distribution</h3> | |
| <canvas id="distribution-chart"></canvas> | |
| </div> | |
| </div> | |
| <!-- TODO: PROPRIETARY - Advanced AI Analytics Dashboard --> | |
| <div class="mt-6 p-6 bg-blue-50 border-2 border-dashed border-blue-200 rounded-lg"> | |
| <h3 class="text-blue-900 font-semibold mb-2">🚀 Coming Soon: AI-Powered Analytics</h3> | |
| <p class="text-blue-700 text-sm">Advanced predictive analytics, ML-driven insights, and automated recommendations will be available in future updates.</p> | |
| </div> | |
| </div> | |
| </div> | |
| {{%endblock %}} | |
| {{%block app_scripts %}} | |
| <script> | |
| // Alpine.js app instance | |
| function {app_slug}App() {{ | |
| return {{ | |
| loading: false, | |
| selectedItems: [], | |
| async refreshData() {{ | |
| this.loading = true; | |
| htmx.trigger('#data-table', 'load'); | |
| this.loading = false; | |
| }}, | |
| async exportData() {{ | |
| window.location.href = '/apps/{app_slug}/export?format=csv'; | |
| }}, | |
| showNewModal() {{ | |
| // TODO: Implement modal | |
| alert('Create new {config['entity_name']} - Modal coming soon'); | |
| }}, | |
| showImportModal() {{ | |
| // TODO: Implement import | |
| alert('Import {config['entity_name'].lower()}s - Feature coming soon'); | |
| }} | |
| }} | |
| }} | |
| // Initialize charts if on analytics tab | |
| document.addEventListener('alpine:init', () => {{ | |
| // Chart initialization will go here | |
| }}); | |
| </script> | |
| {{%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 "<div>Table goes here</div>" | |
| # ============================================================================ | |
| # 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() | |