""" Smart Clinical Forms Real-time validation and clinical decision support forms """ import json from typing import Any, Dict, List, Optional from core.clinical_workflow import EventType, WorkflowStage, clinical_workflow from fasthtml.common import * # type: ignore[import-untyped] from fasthtml.common import ( # noqa: F811 - explicit for mypy H3, Button, Div, Form, Input, Label, Option, P, Select, Span, Textarea, ) class SmartForm: """Base class for intelligent clinical forms""" def __init__(self, form_id: str, title: str, context: str): self.form_id = form_id self.title = title self.context = context # clinical context for validation self.fields = [] # type: ignore[name-defined, index, return-value, var-annotated] self.validation_rules = {} # type: ignore[name-defined, index, return-value, var-annotated] self.conditional_logic = {} # type: ignore[name-defined, index, return-value, var-annotated] self.real_time_processors = [] # type: ignore[name-defined, index, return-value, var-annotated] def add_field(self, field_config: dict[str, Any]): """Add form field with validation and logic""" self.fields.append(field_config) if "validation" in field_config: self.validation_rules[field_config["name"]] = field_config["validation"] if "show_when" in field_config: self.conditional_logic[field_config["name"]] = field_config["show_when"] def render(self, session_id: str = "", initial_data: dict = None) -> Div: # type: ignore[arg-type, assignment] """Render smart form with real-time capabilities""" initial_data = initial_data or {} form_fields = [] # Form header with progress indicator form_fields.append( Div( H2(self.title, cls="text-2xl font-bold text-gray-900 mb-2"), # type: ignore[name-defined, index, return-value, var-annotated] Div(id=f"{self.form_id}-progress", cls="w-full bg-gray-200 rounded-full h-2 mb-6"), Div(id=f"{self.form_id}-alerts", cls="mb-4"), cls="mb-6", ) ) # Render form fields for field in self.fields: field_element = self._render_field(field, initial_data.get(field["name"], "")) # Add conditional display logic if field["name"] in self.conditional_logic: condition = self.conditional_logic[field["name"]] field_element = Div( field_element, id=f"field-{field['name']}", style=f"display: {'block' if self._evaluate_condition(condition, initial_data) else 'none'}", ) form_fields.append(field_element) # Real-time validation status form_fields.append( Div( Div(id=f"{self.form_id}-validation-summary", cls="mb-4"), Div(id=f"{self.form_id}-recommendations", cls="mb-4"), cls="mt-6", ) ) # Form actions form_fields.append( Div( Button( "Validate Data", type="button", cls="btn btn-secondary mr-3", onclick=f"validateForm('{self.form_id}')", ), Button( "Process & Recommend", type="button", cls="btn btn-primary", onclick=f"processForm('{self.form_id}', '{session_id}')", ), cls="flex gap-3 mt-6", ) ) return Form( *form_fields, id=self.form_id, cls="max-w-4xl mx-auto bg-white p-8 rounded-lg shadow-lg", hx_post=f"/api/forms/{self.form_id}/process", hx_target=f"#{self.form_id}-results", hx_trigger="submit", ) def _render_field(self, field: dict[str, Any], value: Any = "") -> Div: """Render individual form field""" field_type = field.get("type", "text") name = field["name"] label = field.get("label", name.replace("_", " ").title()) required = field.get("required", False) help_text = field.get("help", "") field_div = Div(cls="form-group mb-6") # Field label label_element = Label( label, Span(" *", cls="text-red-500") if required else "", For=name, cls="block text-sm font-semibold text-gray-700 mb-2", ) field_div.appendChild(label_element) # Field input based on type if field_type == "text": input_element = Input( type="text", name=name, id=name, value=str(value) if value else "", required=required, cls="form-input w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500", onchange=f"validateField('{name}', this.value)", placeholder=field.get("placeholder", ""), ) elif field_type == "number": input_element = Input( type="number", name=name, id=name, value=str(value) if value else "", required=required, min=field.get("min"), max=field.get("max"), step=field.get("step", "1"), cls="form-input w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500", onchange=f"validateField('{name}', this.value)", ) elif field_type == "select": options = [ Option(opt.get("label", opt["value"]), value=opt["value"]) for opt in field.get("options", []) ] input_element = Select( *options, name=name, id=name, required=required, cls="form-input w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500", onchange=f"validateField('{name}', this.value); updateConditionalFields()", ) elif field_type == "checkbox_group": input_element = Div( *[ Div( Input( type="checkbox", name=name, value=opt["value"], id=f"{name}_{opt['value']}", cls="mr-2", ), Label( opt.get("label", opt["value"]), For=f"{name}_{opt['value']}", cls="text-sm text-gray-700", ), cls="flex items-center mb-2", ) for opt in field.get("options", []) ], cls="space-y-2", ) elif field_type == "textarea": input_element = Textarea( value if value else "", name=name, id=name, required=required, rows=field.get("rows", 4), cls="form-input w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 resize-vertical", placeholder=field.get("placeholder", ""), ) else: input_element = Input( type=field_type, name=name, id=name, value=str(value) if value else "", required=required, cls="form-input w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500", ) field_div.appendChild(input_element) # Field validation feedback field_div.appendChild(Div(id=f"{name}-feedback", cls="mt-2 text-sm")) # Help text if help_text: field_div.appendChild(P(help_text, cls="mt-1 text-sm text-gray-600")) return field_div def _evaluate_condition(self, condition: dict, data: dict) -> bool: """Evaluate conditional display logic""" field = condition.get("field") operator = condition.get("operator", "equals") value = condition.get("value") if field not in data: return False field_value = data[field] if operator == "equals": return field_value == value elif operator == "not_equals": return field_value != value elif operator == "contains": return value in field_value if isinstance(field_value, (list, str)) else False elif operator == "greater_than": return float(field_value) > float(value) # type: ignore[arg-type, assignment] elif operator == "less_than": return float(field_value) < float(value) # type: ignore[arg-type, assignment] return False class GastricSurgeryForm(SmartForm): """Smart form for gastric surgery assessment""" def __init__(self): super().__init__("gastric_surgery_form", "Gastric Surgery Assessment", "gastric_surgery") # Patient demographics self.add_field( { "name": "patient_age", "type": "number", "label": "Patient Age", "required": True, "min": 0, "max": 120, "validation": {"min": 0, "max": 120}, "help": "Patient age in years", } ) self.add_field( { "name": "gender", "type": "select", "label": "Gender", "required": True, "options": [ {"value": "male", "label": "Male"}, {"value": "female", "label": "Female"}, ], } ) # Tumor characteristics self.add_field( { "name": "tumor_location", "type": "select", "label": "Tumor Location", "required": True, "options": [ {"value": "antrum", "label": "Antrum"}, {"value": "body", "label": "Body"}, {"value": "fundus", "label": "Fundus"}, {"value": "cardia", "label": "Cardia"}, {"value": "gej", "label": "Gastroesophageal Junction"}, {"value": "diffuse", "label": "Diffuse"}, ], } ) self.add_field( { "name": "histology", "type": "select", "label": "Histological Type", "required": True, "options": [ {"value": "intestinal", "label": "Intestinal Type"}, {"value": "diffuse", "label": "Diffuse Type"}, {"value": "mixed", "label": "Mixed Type"}, {"value": "signet_ring", "label": "Signet Ring Cell"}, ], } ) self.add_field( { "name": "clinical_stage", "type": "select", "label": "Clinical T Stage", "required": True, "options": [ {"value": "Tis", "label": "Tis - Carcinoma in situ"}, {"value": "T1", "label": "T1 - Invades lamina propria/submucosa"}, {"value": "T2", "label": "T2 - Invades muscularis propria"}, {"value": "T3", "label": "T3 - Invades subserosa"}, {"value": "T4a", "label": "T4a - Invades serosa"}, {"value": "T4b", "label": "T4b - Invades adjacent organs"}, ], } ) self.add_field( { "name": "lymph_node_status", "type": "select", "label": "Lymph Node Status", "required": True, "options": [ {"value": "N0", "label": "N0 - No regional lymph nodes"}, {"value": "N1", "label": "N1 - 1-2 regional lymph nodes"}, {"value": "N2", "label": "N2 - 3-6 regional lymph nodes"}, {"value": "N3a", "label": "N3a - 7-15 regional lymph nodes"}, {"value": "N3b", "label": "N3b - ≥16 regional lymph nodes"}, ], } ) # Comorbidities self.add_field( { "name": "comorbidities", "type": "checkbox_group", "label": "Comorbidities", "options": [ {"value": "diabetes", "label": "Diabetes Mellitus"}, {"value": "cardiac_disease", "label": "Cardiac Disease"}, {"value": "pulmonary_disease", "label": "Pulmonary Disease"}, {"value": "renal_disease", "label": "Renal Disease"}, {"value": "liver_disease", "label": "Liver Disease"}, {"value": "previous_surgery", "label": "Previous Abdominal Surgery"}, ], } ) # Laboratory values self.add_field( { "name": "albumin_level", "type": "number", "label": "Serum Albumin (g/dL)", "step": "0.1", "min": "1.0", "max": "6.0", "help": "Normal range: 3.5-5.0 g/dL", } ) self.add_field( { "name": "hemoglobin", "type": "number", "label": "Hemoglobin (g/dL)", "step": "0.1", "min": "4.0", "max": "20.0", "help": "Normal range: 12-16 g/dL (female), 14-18 g/dL (male)", } ) # Conditional fields based on comorbidities self.add_field( { "name": "hba1c_level", "type": "number", "label": "HbA1c (%)", "step": "0.1", "show_when": { "field": "comorbidities", "operator": "contains", "value": "diabetes", }, "help": "Required for diabetic patients", } ) self.add_field( { "name": "ejection_fraction", "type": "number", "label": "Left Ventricular Ejection Fraction (%)", "min": "10", "max": "100", "show_when": { "field": "comorbidities", "operator": "contains", "value": "cardiac_disease", }, "help": "Required for patients with cardiac disease", } ) # Neoadjuvant therapy self.add_field( { "name": "neoadjuvant_therapy", "type": "select", "label": "Neoadjuvant Therapy Plan", "options": [ {"value": "none", "label": "No neoadjuvant therapy"}, {"value": "flot", "label": "FLOT Protocol"}, {"value": "ecf", "label": "ECF Protocol"}, {"value": "dcf", "label": "DCF Protocol"}, {"value": "other", "label": "Other protocol"}, ], "show_when": {"field": "clinical_stage", "operator": "contains", "value": "T3"}, } ) class ClinicalAssessmentForm(SmartForm): """Smart form for general clinical assessment""" def __init__(self): super().__init__("clinical_assessment_form", "Clinical Assessment", "clinical") # Chief complaint self.add_field( { "name": "chief_complaint", "type": "textarea", "label": "Chief Complaint", "required": True, "rows": 3, "placeholder": "Describe the patient's primary concern or symptoms", } ) # History of present illness self.add_field( { "name": "history_present_illness", "type": "textarea", "label": "History of Present Illness", "required": True, "rows": 5, "placeholder": "Detailed description of current symptoms and timeline", } ) # Vital signs self.add_field( { "name": "blood_pressure_systolic", "type": "number", "label": "Blood Pressure - Systolic (mmHg)", "min": "50", "max": "300", "required": True, } ) self.add_field( { "name": "blood_pressure_diastolic", "type": "number", "label": "Blood Pressure - Diastolic (mmHg)", "min": "30", "max": "200", "required": True, } ) self.add_field( { "name": "heart_rate", "type": "number", "label": "Heart Rate (bpm)", "min": "30", "max": "250", "required": True, } ) self.add_field( { "name": "temperature", "type": "number", "label": "Temperature (°C)", "step": "0.1", "min": "30.0", "max": "45.0", "required": True, } ) # Assessment and plan self.add_field( { "name": "assessment", "type": "textarea", "label": "Clinical Assessment", "rows": 4, "placeholder": "Clinical impression and differential diagnosis", } ) self.add_field( { "name": "plan", "type": "textarea", "label": "Treatment Plan", "rows": 4, "placeholder": "Diagnostic workup and treatment recommendations", } ) # JavaScript for real-time form functionality SMART_FORM_SCRIPT = """ // Real-time form validation and processing let formData = {}; let validationResults = {}; async function validateField(fieldName, value) { // Store field value formData[fieldName] = value; // Basic client-side validation const feedback = document.getElementById(fieldName + '-feedback'); if (!feedback) return; // Clear previous feedback feedback.innerHTML = ''; feedback.className = 'mt-2 text-sm'; try { // Send validation request const response = await fetch('/api/validate-field', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ field: fieldName, value: value, context: getCurrentFormContext() }) }); const result = await response.json(); if (result.valid) { feedback.innerHTML = '✓ Valid'; feedback.className += ' text-green-600'; } else { feedback.innerHTML = '✗ ' + result.message + ''; feedback.className += ' text-red-600'; } // Update validation results validationResults[fieldName] = result; // Update progress updateProgress(); } catch (error) { console.error('Validation error:', error); feedback.innerHTML = 'Validation error'; } } async function validateForm(formId) { const form = document.getElementById(formId); const formData = new FormData(form); const data = Object.fromEntries(formData.entries()); try { const response = await fetch('/api/validate-form', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ form_id: formId, data: data }) }); const result = await response.json(); displayValidationSummary(formId, result); } catch (error) { console.error('Form validation error:', error); } } async function processForm(formId, sessionId) { const form = document.getElementById(formId); const formData = new FormData(form); const data = Object.fromEntries(formData.entries()); // Show processing state const processBtn = event.target; processBtn.disabled = true; processBtn.innerHTML = 'Processing...'; try { const response = await fetch('/api/process-clinical-data', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ session_id: sessionId, form_id: formId, data: data }) }); const result = await response.json(); // Display results displayProcessingResults(formId, result); // Show recommendations if (result.recommendations && result.recommendations.length > 0) { displayRecommendations(formId, result.recommendations); } } catch (error) { console.error('Processing error:', error); alert('Error processing form data. Please try again.'); } finally { processBtn.disabled = false; processBtn.innerHTML = 'Process & Recommend'; } } function displayValidationSummary(formId, validation) { const summaryDiv = document.getElementById(formId + '-validation-summary'); if (!summaryDiv) return; let html = '
'; html += '

Validation Summary

'; if (validation.is_valid) { html += '

✓ All required fields are valid

'; } else { html += '
'; html += '

Issues found:

'; html += '
'; } if (validation.warnings && validation.warnings.length > 0) { html += '
'; html += '

Warnings:

'; html += '
'; } html += '
'; html += 'Quality Score: '; html += '' + Math.round(validation.quality_score * 100) + '%'; html += '
'; html += '
'; summaryDiv.innerHTML = html; } function displayRecommendations(formId, recommendations) { const recDiv = document.getElementById(formId + '-recommendations'); if (!recDiv || !recommendations.length) return; let html = '
'; html += '

Clinical Recommendations

'; recommendations.forEach((rec, index) => { const priorityColor = rec.priority === 'urgent' ? 'red' : rec.priority === 'high' ? 'orange' : 'blue'; html += '
'; html += '
'; html += '

' + rec.title + '

'; html += '' + rec.priority + ''; html += '
'; html += '

' + rec.description + '

'; html += '
'; html += 'Evidence Level: ' + rec.evidence_level + ''; html += 'Confidence: ' + Math.round(rec.confidence * 100) + '%'; html += '
'; html += '
'; }); html += '
'; recDiv.innerHTML = html; } function updateConditionalFields() { // Handle conditional field display logic // This would be expanded based on specific form logic } function updateProgress() { // Calculate and update form completion progress const totalFields = Object.keys(validationResults).length; const validFields = Object.values(validationResults).filter(r => r.valid).length; const progress = totalFields > 0 ? (validFields / totalFields) * 100 : 0; const progressBars = document.querySelectorAll('[id$="-progress"]'); progressBars.forEach(bar => { bar.innerHTML = '
'; }); } function getCurrentFormContext() { // Determine current form context for validation if (document.getElementById('gastric_surgery_form')) return 'gastric_surgery'; if (document.getElementById('clinical_assessment_form')) return 'clinical'; return 'general'; } """